Home > front end >  Regular Expressions (Regex) 2 expressions: remove spaces before verifying 2nd one
Regular Expressions (Regex) 2 expressions: remove spaces before verifying 2nd one

Time:10-25

TLDR:

I have option to add only one regex.

How to make those 2 expressions:

  • \s
  • (\d{10})(19|20)(\d{2})$:$1$3

work at the same time (one after another) and not separately?

This is not enough: \s|(\d{10})(19|20)(\d{2})$:$1$3

Long description:

I have an expression: '(\d{10})(19|20)(\d{2})$:$1$3'

What it does:

  • user password should have 12 digits - ending with last 2 digits of the year
  • in case phrase has 14 digits (someone added full year) - ignore digits 11th and 12th

Thanks to that we can accept both codes: 308814310175 and 30881431011975.

Now I'm looking for a way to ignore spaces in case user adds them anywhere by mistake (not my requirement).

Theoretically I can just add '|\s', to get '\s|(\d{10})(19|20)(\d{2})$:$1$3'.

Both regex works separately:

  • when someone adds full year - it removes 11th and 12th digits
  • when someone adds space - it removes it but if someone adds space AND adds full year then only removing of spaces works (because phrase is longer than 14 digits).

So this works:

  • 308814310175
  • 30881431011975
  • 3088143 10119

But this is not working:

  • 3088143101 1975

because it removes space OR 11th/12th digits - not making both things work one after another.

How to make both expressions work at the same time?

Thank you in advance for your help.

CodePudding user response:

A somewhat long solution would be to capture any digit seperately and avoid spaces and a possible 11th and 12 digit in case of 14 digits total:

^\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(\d)\s*(?:1\s*9|2\s*0)?\s*(\d)\s*(\d)\s*$

See an online demo. You would then replace this with $1$2$3$4$5$5$6$7$8$9$10$11$12


Another possibility (if supported) could be to replace:

(?:[^\S\n]|(?<=^\s*(?:\d\s*?){10})\s*(?:1\s*9|2\s*0)(?=\s*\d\s*\d\s*$))

With nothing. But this would require zero-width lookbehind. See demo

CodePudding user response:

You are trying to solve a simple problem in a complicated way. Instead of using a complicated regex, just use two simple steps:

  1. Remove unwanted spaces.
  2. Apply the regex to validate the string and remove other unwanted characters.
  • Related