怎样使用正则表达式跳过包含特定单词的字符串。

huangapple go评论62阅读模式
英文:

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 = &quot;[0-9]+\\h+Vehicles(?!\\h+have\\b)&quot;;
英文:

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)

Regex demo

In Java

String regex = &quot;[0-9]+\\h+Vehicles(?!\\h+have\\b)&quot;;

huangapple
  • 本文由 发表于 2020年8月18日 15:33:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63463841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定