javascript - 使用正则表达式匹配一次空字符串、逗号、连字符或下划线

标签 javascript html regex match

我正在尝试找出如何匹配以下字符串:

blaOSXbla
os X bla
bla os-x
blablaOS_Xbla

一个常见的模式非常简单:/(osx|os x|os-x|os_x)/i.test(string)

任务是尽可能地减少它。所以我的下一步是 /(os)x| x|-x|_x)/i.test(string).

我也尝试过 /os(.*?)x/ 模式,但它匹配 osx 之间的任意数量的符号>。如何让它匹配零个或一个符号

最佳答案

您需要使用 character class :

/os[ _-]?x/i

参见 demo

With a "character class", also called "character set", you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets. If you want to match an a or an e, use [ae].

A character class matches only a single character. gr[ae]y does not match graay, graey or any such thing. The order of the characters inside a character class does not matter. The results are identical.

您需要 ? 来使匹配成为可选的。

参见 "Optional Items" :

The question mark makes the preceding token in the regular expression optional. colou?r matches both colour and color. The question mark is called a quantifier.

关于javascript - 使用正则表达式匹配一次空字符串、逗号、连字符或下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31429245/

相关文章:

javascript - 事件处理函数上的全局变量和局部变量

javascript - 是否可以像这样用 CSS 剪切 DIV 的一侧?

javascript - 我们如何检测元素外的双击?

python - 根据第一个字符的出现分隔字符串列

javascript - 我需要在正则表达式中转义破折号吗?

javascript - 在React.js中从父组件调用子组件函数

javascript - getElementById 在本地测试但在 JSFiddle 中工作时返回 null

javascript - 为什么 W3schools 图标没有动画

javascript - Webkit 中的同步重绘/等待 DOM 更新?

用于特定区域外匹配的 C# 正则表达式