正则表达式中的可选字符 [英] Optional characters in a regex

查看:98
本文介绍了正则表达式中的可选字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任务非常简单,但是我还无法提出一个好的解决方案:字符串可以包含数字,破折号和加号,或者只能包含数字.

The task is pretty simple, but I've not been able to come up with a good solution yet: a string can contain numbers, dashes and pluses, or only numbers.

^[0-9+-]+$

满足我的大部分需求,除非用户输入"+-+-+"之类的垃圾

does most of what I need, except when a user enters garbage like "+-+--+"

我还没有经常走前路的运气,因为破折号和加号可能位于字符串中的任何地方.

I've not had luck with regular lookahead, since the dashes and pluses could potentially be anywhere in the string.

有效字符串:

  1. 234654
  2. 24-3 + -2
  3. -234
  4. 25485 +

无效:

  1. ++-+

推荐答案

怎么样:

^[0-9+-]*[0-9][0-9+-]*$

这确保字符串中的某处至少有一个数字. (虽然看起来可能有很多回溯.但是,另一方面,它没有在另一个+或*内包裹+或*,我也不喜欢.)

This ensures that there is at least one digit somewhere in the string. (It looks like it might have a lot of backtracking, though. But on the other hand it doesn't have a + or * wrapped inside another + or *, which I don't like either.)

这篇关于正则表达式中的可选字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆