Moh*_*uur 6 java regex string split
我有点试图用正则表达式来破解具有以下属性的字符串:
例如,这里有一些我想要分解的字符串:
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;
}
Run Code Online (Sandbox Code Playgroud)
Ala*_*ore 13
诀窍是不使用该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));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
One|Two|Three
[One, Two, Three]
One\|Two\|Three
[One|Two|Three]
One\\|Two\|Three
[One\, Two|Three]
One\\\|Two
[One\|Two]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6371 次 |
| 最近记录: |