Home > Enterprise >  Regular expression for presuffix and suffix with characters and numbers
Regular expression for presuffix and suffix with characters and numbers

Time:11-25

I am trying to prepare the regular expression for below mentioned formats to accept. I tried some options which did not work and getting the error like "pattern syntax exception: error parsing regexp: invalid nested repetition operator: ?

abc 12345678 - should be true
abc12345678abc - should be true
#12345678 - should be true
12345678# - should be true
12345678 - should be false

I have tried below

^([a-zA-Z]) ? ([0-9]{8}) ? ([a-zA-Z])|([a-zA-Z]) ? ([0-9]{8})|([0-9]{8}) ? ([a-zA-Z])|(# ? )([0-9]{8})( ?# )|(# ? )([0-9]{8})|([0-9]{8})( ?# )

CodePudding user response:

? from your regex is an optional but posessive quantifier which javascript doesn't support (at least in this syntax) demo here: https://regex101.com/r/aLOqhS/1 (see error on right hand side)

Solution would be to use quantifiers and methods supported by JS, one such attempt:

(?<=^[a-zA-Z#\s] )\d |\d (?=[a-zA-Z#\s] $)

demo here: https://regex101.com/r/9moHi8/1

  • Related