[英]java regex split string
我有點試圖用正則表達式來破解具有以下屬性的字符串:
例如,這里有一些我想要分解的字符串:
One|Two|Three
應該屈服: ["One", "Two", "Three"]
One\\|Two\\|Three
應該產生: ["One|Two|Three"]
One\\\\|Two\\|Three
應該產生: ["One\\", "Two|Three"]
現在我怎么能用一個正則表達式將它拆分?
更新:正如你們許多人已經建議的那樣,這不是正則表達式的一個很好的應用。 此外,正則表達式解決方案比僅迭代字符慢幾個數量級。 我最終迭代了角色:
public static List<String> splitValues(String val) {
final List<String> list = new ArrayList<String>();
boolean esc = false;
final StringBuilder sb = new StringBuilder(1024);
final CharacterIterator it = new StringCharacterIterator(val);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
if(esc) {
sb.append(c);
esc = false;
} else if(c == '\\') {
esc = true;
} else if(c == '|') {
list.add(sb.toString());
sb.delete(0, sb.length());
} else {
sb.append(c);
}
}
if(sb.length() > 0) {
list.add(sb.toString());
}
return list;
}
訣竅是不使用split()
方法。 這會強制您使用lookbehind來檢測轉義字符,但是當轉義本身被轉義時(如您所發現的那樣),這會失敗。 您需要使用find()
來匹配標記而不是分隔符:
public static List<String> splitIt(String source)
{
Pattern p = Pattern.compile("(?:[^|\\\\]|\\\\.)+");
Matcher m = p.matcher(source);
List<String> result = new ArrayList<String>();
while (m.find())
{
result.add(m.group().replaceAll("\\\\(.)", "$1"));
}
return result;
}
public static void main(String[] args) throws Exception
{
String[] test = { "One|Two|Three",
"One\\|Two\\|Three",
"One\\\\|Two\\|Three",
"One\\\\\\|Two" };
for (String s :test)
{
System.out.printf("%n%s%n%s%n", s, splitIt(s));
}
}
輸出:
One|Two|Three
[One, Two, Three]
One\|Two\|Three
[One|Two|Three]
One\\|Two\|Three
[One\, Two|Three]
One\\\|Two
[One\|Two]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.