Match empty string, comma, hyphen or underscore once using regex

后端 未结 2 1997
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 14:28

I\'m trying to figure out how to match the following strings:

blaOSXbla
os X bla
bla os-x
blablaOS_Xbla

A common pattern is pretty easy:

相关标签:
2条回答
  • 2021-01-21 14:50

    Try:

    /os[ \-_]?x)/i.test(string)
    

    Use ? to match the previous set zero or one time.

    Demo

    0 讨论(0)
  • 2021-01-21 14:59

    You need to use a character class:

    /os[ _-]?x/i
    

    See 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.

    And you need ? to make the match optional.

    See "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.

    0 讨论(0)
提交回复
热议问题