Home > Software engineering >  Javascript Regex to match only zero/even number of backslashes anywhere in a string
Javascript Regex to match only zero/even number of backslashes anywhere in a string

Time:01-20

I need a regular expression that matches the complete string with a zero/even number of backslashes anywhere in the string. If the string contains an odd number of backslashes, it should not match the complete string.

Example:

\\ -> match

\\\ -> does not match

test\\test -> match

test\\\test-> does not match

test\\test\ -> does not match

test\\test\\ -> match

and so on... Note: We can assume any string of any length in place of 'test' in the above example

I am using this ^[^\\]*(\\\\)*[^\\]*$ regular expression, but it does not match the backslashes after the second test. For example:

test\\test(doesn't match anything after this)

Thanks for any help in advance.

CodePudding user response:

The current regular expression ^[^\\]*(\\\\)*[^\\]*$ can be interpreted as Any(\\)*Any, Where Any means any character except backslash.

The expected language shall be Any\\Any\\Any\\..., which can be obtained by containing the current regular expression in Kleene closure operator. That is (Any(\\)*Any)*

The original regular expression after modification:

^([^\\]*(\\\\)*[^\\]*)*$

It can be further optimized as:

^((\\\\)*[^\\]*)*$

CodePudding user response:

You may use this regex:

^(?:(?:[^\\]*\\){2})*[^\\]*$

RegEx Demo

RegEx Breakdown:

  • ^: Start
  • (?:: Start non-capture group #1
    • (?:: Start non-capture group #2
      • [^\\]*: Match 0 or more og any char except a \
      • \\: Match a \
    • ){2}: End non-capture group #2. Repeat this group 2 times.
  • )*: End non-capture group #1. Repeat this group 0 or more times.
  • [^\\]*: Match 0 or more og any char except a \
  • $: End
  • Related