简体   繁体   English

即使不存在匹配项,Java 正则表达式负前瞻也会返回匹配项

[英]Java regex- negative lookahead returning a match even when a match shouldn't exist

I have a string as follows:我有一个字符串如下:

<marker name="my.marker" cachedBy="all" affectedBy="typ1,type2">
<child1>bla</child1>
</marker>

What I would like to do is a lookup to identify the first occurrence of > using the following condition.我想做的是使用以下条件查找第一次出现的>

  1. Match > if the line doesn't have affectedBy= attribute available eg affectedBy="type1" .匹配>如果该行没有可用的affectedBy="type1" affectedBy=属性,例如affectedBy="type1" Because I would like to append it to that line.因为我想将它附加到该行。 So I don't want it to be duplicated eg affectedBy="type1,type2", affectedBy="type1,type2"所以我不希望它被复制,例如affectedBy="type1,type2", affectedBy="type1,type2"

  2. Match only the firs occurrence of > - ie not a global match.只匹配第一次出现的> - 即不是全局匹配。

I tried the following:我尝试了以下方法:

<(?!=(.*sharedBy=".*"))>

But it returns a match for > even when affectedBy= is present.但它会返回一个>匹配项,即使存在affectedBy=也是如此。 I am sure this might be something wrong in my lookahead logic, but cannot figure it out.我确信这在我的前瞻逻辑中可能有问题,但无法弄清楚。 Any help would be appreciated.任何帮助,将不胜感激。

I simply did the following:我只是做了以下事情:

1) If anything Matches affectedBy=.*> ignore it. 1) 如果有任何匹配affectedBy=.*>忽略它。

2) Otherwise, find the first group matching (?=<marker name="my.marker".*)?> , and then replace > with affectedBy="type1,type2>" 2) 否则,找到匹配的第一组(?=<marker name="my.marker".*)?> ,然后将>替换为(?=<marker name="my.marker".*)?> affectedBy="type1,type2>"

Didn't want to write XML parsing.不想写 XML 解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM