2016-04-05 20 views
0

我有很简单的regex代码:简单的正则表达式转化未返回完整的单词

(project-(?!old|rejected)) 

我有这样的字符串列表:

project-ok 2016/3/4 
project-new 2016/4/5 
project-in-progress 2015/3/8 
project-cancel 2014/2/7 
project-rejected 2011/9/2 
... etc. 

我想捕捉,除了项目的老项目什么和项目被拒绝。

尝试匹配该行时:project-ok 2016/3/4。我希望它返回'项目'好'但我得到的返回值:'项目''只。

如何匹配项目标签的完整字词?

+0

['(project-(?!old | rejected)\ S +)'](https://regex101.com/r/sC7iV6/1) – Tushar

+0

@Tushar:非常感谢。 – andio

回答

1

让我们来看看你正在尝试与(project-(?!old|rejected))

  • project-比赛办。

  • (?!old|rejected)展望未来,并检查是否存在oldrejected。如果是,则不匹配。但是,没有什么做的后不存在

所以你需要,直到空白被发现的标签相匹配。这可以通过在先前的条件之后使用\S+[^\s]+来完成。

完整的正则表达式应该是这样的:project-(?!old|rejected)[^\s]+

Regex101 Demo

1

尝试

project-(?!old\s|rejected\s)[-a-z]+

https://regex101.com/r/wX2eY8/3

+0

也许可以解释为什么这是更好的工作。负面预测本身仅控制正则表达式引擎在匹配以下文本时可能不会采用的分支。 – tripleee

0

你可以试试这个:

(?i)(project-(?!old|rejected)\b[-0-9a-z/ ]+) 

而且这里去相同的解剖结构:

(?i)     # Match the remainder of the regex with the options: case insensitive (i) 
(     # Match the regular expression below and capture its match into backreference number 1 
    project-    # Match the characters “project-” literally 
    (?!     # Assert that it is impossible to match the regex below starting at this position (negative lookahead) 
          # Match either the regular expression below (attempting the next alternative only if this one fails) 
     old     # Match the characters “old” literally 
     |     # Or match regular expression number 2 below (the entire group fails if this one fails to match) 
     rejected    # Match the characters “rejected” literally 
    ) 
    \\b     # Assert position at a word boundary 
    [-0-9a-z/ ]   # Match a single character present in the list below 
          # The character “-” 
          # A character in the range between “0” and “9” 
          # A character in the range between “a” and “z” 
          # One of the characters “/ ” 
     +     # Between one and unlimited times, as many times as possible, giving back as needed (greedy) 
) 

希望这可以帮助。