java - 使用正则表达式和条件分割字符

标签 java regex split

我尝试用以下条件分割字符串

  • 保留所有字符
  • 拆分=如果前面的字符不是 %!
  • 拆分!=

示例:

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中检查等号是否存在:

(?<=!=)|(?=!=)|((?<=(?<![!%])=)|(?=(?<![!%])=))

参见this demo

我修改了这部分:((?<=(?<![!%])=)|(?=(?<![!%])=)) .

( 
 (?<=(?<![!%])=) - 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/

相关文章:

r - 将数字向量拆分为具有连续数字的不同 thunk

excel - 分割多维数组然后对其进行切片

java - 无法编译的源代码 - 不是 arrays.main(arrays.java :4) Java Result: 1 处的语句

java - 无效的 Int,R.array.name

java - 无法通过 tomcat 中的 websocket 发送二进制消息,但可以在 glassfish 中使用。在 tomcat 中失败并出现 IllegalArgumentException

javascript - 在 Javascript 中测试 Int 值(正则表达式)

regex - REGEX 表达式的简化

java - 在哪里可以找到 Hibernate 的 DTD?

JavaScript: "Dynamic"反向引用正则表达式替换

c++ - 知道其公共(public) ID 的拆分数据