简体   繁体   English

Javascript 多个单词的正则表达式

[英]Javascript regular expression for multiple words

I am trying to make a regular expression that will account for the possible words "-hello,", "hello,", "-money,", "money," and it will replace these words if they exist, my current code is like我正在尝试制作一个正则表达式来解释可能的单词“-hello”、“hello”、“-money”、“money”,如果它们存在,它将替换这些单词,我当前的代码是喜欢

let regex = /(-?hello,-?money)/gi

but this doesnt work please help me find where this goes wrong, thank you但这不起作用请帮我找出问题所在,谢谢

Use the |使用| (Alternation) instead of the comma. (交替)而不是逗号。

let regex = /(-?hello|-?money)/gi

You might also use an alternation only for the words and surround it with word boundaries \b to prevent partial matches.您也可以仅对单词使用交替,并用单词边界\b将其包围以防止部分匹配。

let regex = /-?\b(?:hello|money)\b/gi
  • -? Match an optional hyphen匹配可选连字符
  • \b A word boundary \b一个词的边界
  • (?: Non capture group (?:非捕获组
    • hello Match literally hello匹配字面意思
    • | Or或者
    • money Match literally money匹配字面意思
  • ) Close non capture group )关闭非捕获组
  • \b A word boundary \b一个词的边界

Regex demo正则表达式演示

 let regex = /-?\b(?:hello|money)\b/gi; [ "-hello", "hello", "-money", "money", "test money nomoney", "test -hello hellow" ].forEach(s => console.log(s.replace(regex, "[replacement]")));

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

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