繁体   English   中英

正则表达式允许模式以可选的特定字符开头,但没有其他字符

[英]Regex that allows a pattern to start with a an optional, specific character, but no other character

如何编写允许模式以特定字符开头的正则表达式,但该字符是可选的?

例如,我想匹配单词“hello”的所有实例,其中“hello”要么在行的开头,要么前面有一个“!”,在这种情况下,它不必在行的开头线。 所以这里的前三个选项应该匹配,但不是最后一个:

hello
!hello
some other text !hello more text
ahello

我对 JavaScript 特别感兴趣。

匹配: /^hello|!hello/g

如果^位于行的开头,则^只会抓取单词“hello”。

| 作为 OR 工作。

 var str = "hello\\n!hello\\n\\nsome other text !hello more text\\nahello"; var regex = /^hello|!hello/g; console.log( str.match(regex) );

编辑:

如果您尝试匹配以下评论中建议的以“hello”开头或包含“!hello”的整行,请使用以下正则表达式:

/^.*(^hello|!hello).*$/gm

 var str = "hello\\n!hello\\n\\nsome other text !hello more text\\nahello"; var regex = /^.*(^hello|!hello).*$/gm; console.log(str.match(regex));

最终解决方案(希望如此)

看起来,捕获groups仅在ECMAScript 2020可用。 链接 1链接 2

作为一种解决方法,我找到了以下解决方案:

 const str = `hello !hello some other text !hello more text ahello this is a test hello !hello JvdV is saying hello helloing or helloed =).`; function collectGroups(regExp, str) { const groups = []; str.replace(regExp, (fullMatch, group1, group2) => { groups.push(group1 || group2); }); return groups; } const regex = /^(hello)|(?:!)(hello\\b)/g; const groups = collectGroups(regex, str) console.log(groups)


/(?=!)?(\\bhello\\b)/g应该这样做。 游乐场

例子:

 const regexp = /(?=!)?(\\bhello\\b)/g; const str = ` hello !hello some other text !hello more text ahello `; const found = str.match(regexp) console.log(found)

解释:

  • (?=!)?

    • (?=!)积极向前看
    • ? 是可选的
  • (\\bhello\\b) : 捕获组

    • \\b单词边界确保hello之前或之后没有字符

注意:如果你也确定,那个hello不应该由! ,那么你可以简单地添加一个负前瞻,像这样/(?=!)?(\\bhello\\b)(?!!)/g


更新

感谢@JvdV 在评论中的提示,我现在已经调整了正则表达式,它应该满足您的要求:

/(^hello\b)|(?:!)(hello\b)/gm

Playground: https : //regex101.com/r/CXXPHK/4 (解释也可以在页面上找到)。


更新 2:

看起来非捕获组(?:!)在 JavaScript 中不能很好地工作,即我得到一个匹配结果,如["hello", "!hello", "!hello", "!hello"] ,其中! 也包括在内。 但谁在乎,这里有一个解决方法:

const regex = /(^hello\b)|(?:!)(hello\b)/gm;
const found = (str.match(regex) || []).map(m => m.replace(/^!/, ''));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM