gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:19 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com