在特定单词之外的任何其他字符的中间找到一组特定的字符

时间:2018-01-15 17:16:52

标签: regex

我有正则表达式问题。我试图在任何单词的中间找到一组特定的字符(%.o:%.cpp不区分大小写)。

我们发现的问题是,这会返回rmsformShow之类的内容。所以我们试着编写一些正则表达式来缩小搜索范围。

检查stackoverflow上的其他问题我创建了以下内容:

forms

然而,这似乎与我们提出的任何测试示例都不相符。

^(?!.*forms).*rms.*$

如何将搜索限制为包含rms的任何内容,但排除其中包含rms (should match) RMS (should match) rMs (should match) forms (should not match) tfrmrmsexport (should match) formshow (should not match) 的内容?

2 个答案:

答案 0 :(得分:3)

代码

下面的所有正则表达式模式都使用i(不区分大小写)标记。

See regex in use here

\b(?!\w*forms)\w*rms\w*

备选方案:

\b(?:(?!forms)\w)*rms\w*
\b\w*(?<!fo)rms\w*           #As proposed by Aaron in comments beneath the question

<子> Link to Aaron's user profile here

说明

  • \b断言位置为单词边界
  • (?!\w*forms)否定前瞻确保单词
  • 中不存在forms
  • \w*匹配任意数量的字符
  • rms按字面意思匹配
  • \w*匹配任意数量的字符

答案 1 :(得分:0)

或者,如果在空白的中间寻找有效值,则更复杂的形式 有界的字母组。

这会产生更好的效果,因为 \w只是一个字符类
不应该被语言中的单词定义所混淆。

(?i)(?<!\S)(?:(?!forms)\S)*rms(?:(?!forms)\S)*(?!\S)

格式化

 (?i)                          # Case insensitive modifier
 (?<! \S )                     # Whitespace boundary
 (?:                           # Before 'rms'
      (?! forms )                   # Not 'forms' ahead 
      \S                            # Non-whitespace char
 )*                            # 0 to many times

 rms                           # The 'rms' we need

 (?:                           # After 'rms'
      (?! forms )                   # Not 'forms' ahead 
      \S                            # Non-whitespace char
 )*                            # 0 to many times
 (?! \S )                      # Whitespace boundary
相关问题