简体   繁体   English

将php正则表达式转换为javascript

[英]Converting php regex to javascript

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 "(?" 到javascript中,但面临转义或处理“(?

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 我尝试在https://regex101.com/#javascript验证,但无法处理,任何人都可以分享需要在上述regex中修复的内容,以便它可以在javascript中工作

JavaScript doesn't support partial case insensitive patterns. JavaScript不支持部分不区分大小写的模式。 So (?:i is invalid in JS. 因此(?:i在JS中无效。

Use i flag to make the regex in-case-sensitive 使用i标志使正则表达式区分大小写

/^(?:\d{12}|\d{9}|(YHZ)?\d{6}|(YHZ)?\d{8})$/i

Regex 101 Demo 正则表达式101演示


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 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

Regex101 Demo 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> 

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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