正则表达式允许空字符串或具有特定长度的字符串(Regular Expression to allow an empty string or a string with specific length)

编程入门 行业动态 更新时间:2024-10-22 23:30:04
正则表达式允许空字符串或具有特定长度的字符串(Regular Expression to allow an empty string or a string with specific length)

嗨,我无法尝试创建一个正则表达式,允许我将字段设置为空,或者填充长度为9的字符串。

目前使用的正则表达式是: ^[0-9]{9}

如果该字段是必填字段,则该字段有效,但是我们有一个新要求,即它也可以为空。 我已经尝试了^[0-9]{0|9 },但显然不起作用。

提前致谢

Hi I am having trouble trying to create a regex that will allow me to have the field empty or a string with length 9 if populated.

The current regex im using is: ^[0-9]{9}

Which works if the field is mandatory, however we have a new requirement that this can also be empty. I've tried ^[0-9]{0|9} but obviously that doesnt work.

Thanks in advance

最满意答案

^(|[0-9]{9})$

应该做的伎俩。

编辑:但认真; 做@Felix Kling在评论中建议:通过.length属性, .equals("")等测试字符串。

^(|[0-9]{9})$

Should do the trick.

Edit: But seriously; do what @Felix Kling suggests in a comment: test the string via a .length property, .equals("") or the like.

更多推荐

本文发布于:2023-08-07 00:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1457844.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   长度   空字符串   正则表达式   Regular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!