Reputation: 55
I am trying to convert following regex:
^(?:\d{12}|\d{9}|(?i:YHZ)?\d{6}|(?i:YHZ)?\d{8})$
into javascript but facing issues for escaping or handling "(?"
I tried verifying on https://regex101.com/#javascript
but unable to handle it can anyone please share what needs to fix in the above regex so it can work in javascript
Upvotes: 0
Views: 41
Reputation: 55
input:valid {
color: green;
}
input:invalid {
color: red;
}
<input type="text" pattern="((yhz|YHZ)?[0-9]{6}([0-9]{2})?|([0-9]{6})(([0-9]{2,3})|([0-9]{6}))?)" />
<br />
<br />it validates for following cases
<ul>
<li>yhz + 6numeric</li>
<li>yhz + 8numeric</li>
<li>6 numeric</li>
<li>8 numeric</li>
<li>9 numeric</li>
<li>12 numeric</li>
</ul>
input:valid {
color: green;
}
input:invalid {
color: red;
}
<input type="text" pattern="((yhz|YHZ)?[0-9]{6}([0-9]{2})?|([0-9]{6})(([0-9]{2,3})|([0-9]{6}))?)" />
<br />
<br />it validates for following cases
<ul>
<li>yhz + 6numeric</li>
<li>yhz + 8numeric</li>
<li>6 numeric</li>
<li>8 numeric</li>
<li>9 numeric</li>
<li>12 numeric</li>
</ul>
Upvotes: 0
Reputation: 87203
JavaScript doesn't support partial case insensitive patterns. So (?:i
is invalid in JS.
Use i
flag to make the regex in-case-sensitive
/^(?:\d{12}|\d{9}|(YHZ)?\d{6}|(YHZ)?\d{8})$/i
From Comments:
it validates for following cases a. yhz+6numeric (not case sensitive for the yhz) b. yhz+8numeric (not case sensitive for the yhz) c. 6numeric d. 8numeric e. 9numeric f. 12numeric
The regex can be rewritten as
/^((yhz)?[0-9]{6}([0-9]{2})?|([0-9]{6})(([0-9]{2,3})|([0-9]{6}))?)$/i
Test this regex on Regex101
input:valid {
color: green;
}
input:invalid {
color: red;
}
<input type="text" pattern="((yhz|YHZ)?[0-9]{6}([0-9]{2})?|([0-9]{6})(([0-9]{2,3})|([0-9]{6}))?)" />
<br />
<br />it validates for following cases
<ul>
<li>yhz + 6numeric</li>
<li>yhz + 8numeric</li>
<li>6 numeric</li>
<li>8 numeric</li>
<li>9 numeric</li>
<li>12 numeric</li>
</ul>
If you don't want any capture group, use (?:
at the beginning of group.
/^(?:(?:yhz)?[0-9]{6}(?:[0-9]{2})?|(?:[0-9]{6})(?:(?:[0-9]{2,3})|(?:[0-9]{6}))?)$/i
Upvotes: 4