我尝试使用以下条件拆分字符串
=或!,则按!分隔!=示例:
test=45 ->检验,=,45 测试!= 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));
}
}我找到的“最好”的东西是(?=!=)|(?<=!=)|(?<![!%])((?<==)|(?==)),但我不知道为什么%=会在之后分裂((?<==)似乎被执行了)
左字符和右字符可以是任何ACII表。
结果:
test=45 ->检验,=,45 测试!= 45 ->测试!= test%=45 -> test%=,45 <-应为test%=45 test=%=45 -> test,=,%=,45 <-应该是test,=,%=45 test%==%=45 -> test%=,=,%=,45 <-应该是test%=,=,%=45
有可能用正则表达式和分割法来完成吗?
Note:这只是正则表达式的一部分,用来“轻松”解析数据,所以我可以使用简单的代码来完成,而不是使用正则表达式和拆分,但这不是我想要的。
发布于 2016-01-05 22:20:33
您需要将后视镜移到观景器中,检查是否存在等号:
(?<=!=)|(?=!=)|((?<=(?<![!%])=)|(?=(?<![!%])=))请参阅这个演示
我修改了这个部分:((?<=(?<![!%])=)|(?=(?<![!%])=))。
(
(?<=(?<![!%])=) - 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 %
)https://stackoverflow.com/questions/34621298
复制相似问题