简体   繁体   中英

regex for optional characters

I am using the following regex:

^([W|w][P|p]|[0-9]){8}$

The above regex accepts wp1234567 ( wp +7 digits) also. Whereas expected: WP +6digit or wp +6digit or only 8 digit

For example:

WP123456
wp126456
64535353

Note that [W|w] matches W , w and | , since | inside a character class loses its special meaning of an alternation operator. Also, by setting the grouping (...) around [W|w][P|p]|[0-9] you match 8 occurrences of *the whole sequences of WP or digits.

You should set the correct value in the limited quantifier and remove grouping and use alternation to allow either wp +6 digits or just 8 digits:

^(?:[Ww][Pp][0-9]{6}|[0-9]{8})$

See demo

The regex matches:

  • ^ - start of string (not necessary if you check the whole string with String#matches() )
  • (?:[Ww][Pp][0-9]{6}|[0-9]{8}) - 2 alternatives:
    • [Ww][Pp][0-9]{6} - W or w followed with P or p followed with 6 digits
    • | - or...
    • [0-9]{8} - exactly 8 digits
  • $ - end of string

Other scenarios (just in case):

If you need to match strings consisting of 7 or 8 digits, you need to replace {8} limited quantifier with {7,8} :

^(?:[Ww][Pp][0-9]{6}|[0-9]{7,8})$

And in case you do not want to match Wp123456 or wP123456 , use one more alternation in the beginning:

^(?:(?:WP|wp)[0-9]{6}|[0-9]{8})$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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