我正在尋找一種方法來解析可能會使用的幾個不同終止字符的子字符串。我應該使用不同的方法還是使用正則表達式來排列字符?多個IndexOf的可能性
我當前的代碼使用:
smallstring = bigstring.substring(bigstring.indexOf("starthere"), bigstring.indexOf("endhere"));
最後索引可以是 「]」 或 「;」我需要解析器能夠檢測到並終止子字符串。
我正在尋找一種方法來解析可能會使用的幾個不同終止字符的子字符串。我應該使用不同的方法還是使用正則表達式來排列字符?多個IndexOf的可能性
我當前的代碼使用:
smallstring = bigstring.substring(bigstring.indexOf("starthere"), bigstring.indexOf("endhere"));
最後索引可以是 「]」 或 「;」我需要解析器能夠檢測到並終止子字符串。
使用String
的此split()
方法,它是用於工作的工具:
String[] data = "a,b.c;d".split("[,.;]");
在上述例子中,使用三種不同的分離器(,.;
)的字符串可以使用一個正則表達式被分割。最終的結果是,String[]
稱爲data
,將包含所有被分隔符分離的字符串:
[a, b, c, d]
要檢測結束索引,你可以寫
int endIndex = Math.min(bigstring.indexOf("]"), bigstring.indexOf(";"));
if(endIndex == -1) { endIndex = bigstring.length(); }
String smallString = bigstring.substring(startIndex, endIndex);
如果在起始索引後面有兩個指定字符,它就會奏效,但當它無法處理分號時,它會拋出一個超出邊界異常的索引。太糟糕了,這將是最簡單的方法。非常感謝:-) – 2013-05-01 17:17:11
@AlexBible我假設文件中會有一個結尾字符。如果沒有,上面的(更新的)代碼仍然可以工作,沒有任何例外。 – 2013-05-01 17:53:57
試試這個
String smallstring = bigstring.replaceAll(".*starthere(.*)endhere.*", "$1");
使用正則表達式。 在這裏你可以測試它 http://ocpsoft.org/tutorials/regular-expressions/java-visual-regex-tester/
這最終工作最好,並提供了一個更好的方法來解析我的字符串。謝謝! – 2013-05-01 17:17:54