首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用正则表达式和条件围绕字符拆分

问用正则表达式和条件围绕字符拆分
EN

Stack Overflow用户
提问于 2016-01-05 21:11:14
回答 1查看 110关注 0票数 1

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

  • 保留所有字符
  • 如果前面的字符不是=或!,则按!分隔
  • 分裂围绕!=

示例:

test=45 ->检验,=,45 测试!= 45 ->测试!= test%=45 -> test%=45

码

代码语言:javascript
复制
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:这只是正则表达式的一部分,用来“轻松”解析数据,所以我可以使用简单的代码来完成,而不是使用正则表达式和拆分,但这不是我想要的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-05 22:20:33

您需要将后视镜移到观景器中,检查是否存在等号:

代码语言:javascript
复制
(?<=!=)|(?=!=)|((?<=(?<![!%])=)|(?=(?<![!%])=))

请参阅这个演示

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

代码语言:javascript
复制
( 
 (?<=(?<![!%])=) - 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 %
)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34621298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档