我尝试用以下条件分割字符串
- 保留所有字符
- 拆分
=
如果前面的字符不是%
或!
- 拆分
!=
示例:
test=45 -> [test, =, 45]
test!=45 -> [test, !=, 45]
test%=45 -> [test%=45]
代码:
private static final Map<String[], String> tests = new HashMap<>();
static {
tests.put(new String[]{"test", "=", "45"}, "test=45");
tests.put(new String[]{"test", "!=", "45"}, "test!=45");
tests.put(new String[]{"test%=45"}, "test%=45");
tests.put(new String[]{"test", "=", "%=45"}, "test=%=45");
tests.put(new String[]{"test%=", "=", "%=45"}, "test%==%=45");
}
@org.junit.Test
public void simpleTest() {
String regex = "(?=!=)|(?<=!=)|(?<![!%])((?<==)|(?==))";
for (Map.Entry<String[], String> entry : tests.entrySet()) {
Assert.assertArrayEquals(entry.getKey(), entry.getValue().split(regex));
}
}
我发现的“最好”的东西是 (?=!=)|(?<=!=)|(?<![!%])((?<==)|(?==))
但我不知道为什么 %=
它在之后 split ( (?<==)
似乎被执行)
左右字符可以是ACII表中的任意一个。
结果:
test=45 -> [test, =, 45]
test!=45 -> [test, !=, 45]
test%=45 -> [test%=, 45] <- should be [test%=45]
test=%=45 -> [test, =, %=, 45] <- should be [test, =, %=45]
test%==%=45 -> [test%=, =, %=, 45] <- should be [test%=, =, %=45]
是否可以使用正则表达式和 split 来做到这一点?
注意:这只是正则表达式的一部分,它用于“轻松”解析数据,所以是的,我可以用简单的代码来完成它,而不是使用正则表达式和分割,但这不是我要什么。
最佳答案
您需要将lookbehind移动到lookarounds中检查等号是否存在:
(?<=!=)|(?=!=)|((?<=(?<![!%])=)|(?=(?<![!%])=))
我修改了这部分:((?<=(?<![!%])=)|(?=(?<![!%])=))
.
(
(?<=(?<![!%])=) - matches a location preceded by a = sign that is not preceded with ! or %
|
(?=(?<![!%])=) - matches a location followed by a = sign that is not preceded with ! or %
)
关于java - 使用正则表达式和条件分割字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34621298/