负向前瞻匹配

时间:2017-11-20 15:31:28

标签: regex regex-lookarounds

文本:

4.7.3.0/upgradeScript.sql
4.8.1.0/upgradeScript.sql
5.0.1.0/upgradeScript.sql
5.0.13.0/upgradeScript.sql
5.0.15.0/upgradeScript.sql

需要匹配:

4.7.3.0
4.8.1.0
5.0.1.0
5.0.13.0
5.0.15.0

我尝试使用否定前瞻,并且由于某种原因它匹配所有内容:

\S+(?!\/)

为实现目标,我需要做些什么改变?

2 个答案:

答案 0 :(得分:0)

您的\S+(?!\/)模式的工作方式如下:\S+尽可能多地匹配1个或多个非空白字符(直到字符串/行结尾),然后检查/ 。因为它不存在,所以返回整个字符串/行。

要匹配字符串开头的_以外的1个字符,您可以使用

^[^\/]+

请参阅regex demo

答案 1 :(得分:0)

听起来你想要找到 后跟/的任何连续非空格字符,所以需要积极向前看

\S+(?=\/)


`\S+` matches any non-whitespace character (equal to [^\r\n\t\f\v ])
  `+` Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
Positive Lookahead `(?=\/)`
  Assert that the Regex below matches
  `\/` matches the character `/` literally (case sensitive)

(摘自https://regex101.com/

匹配

4.7.3.0
4.8.1.0
5.0.1.0
5.0.13.0
5.0.15.0

来自

4.7.3.0/upgradeScript.sql
4.8.1.0/upgradeScript.sql
5.0.1.0/upgradeScript.sql
5.0.13.0/upgradeScript.sql
5.0.15.0/upgradeScript.sql

根据OP的要求