英文:
how can I skip a string if it contains some word by using regex
问题
我想要在“Vehicles”单词之后跳过包含“have”的字符串
字符串1 = “已经添加了3辆车”,
字符串2 = “13辆车”
我正在使用的正则表达式 = ([0-9]+)[\s]*Vehicles[\s]*[^have]
所需输出仅为“13辆车”(仅此),但“已经添加了3辆车”也是匹配项...这是不正确的
提前致谢。
英文:
I want to skip the string if it contains 'have' after Vehicles word
str 1 = "3 Vehicles have already been added",
str 2 = "13 Vehicles"
Regex I m using = ([0-9]+)[\s]*Vehicles[\s]*[^have]
output needed is "13 Vehicles"(only) but "3 Vehicles" is also matches..that is not right
Thanks in advance
答案1
得分: 0
你可以使用负向先行断言来断定<code> have</code> 不直接位于右侧。
否定的字符类 [^have]
匹配任一未列出的字符。
[0-9]+\h+Vehicles(?!\h+have\b)
在 Java 中
String regex = "[0-9]+\\h+Vehicles(?!\\h+have\\b)";
英文:
You could use a negative lookahead to assert that <code> have</code> is not directly at the right.
The negated character class [^have]
matches a single char which is not any of the listed chars.
[0-9]+\h+Vehicles(?!\h+have\b)
In Java
String regex = "[0-9]+\\h+Vehicles(?!\\h+have\\b)";
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论