在正则表达式中,匹配一个或另一个,或两者 [英] In a regular expression, match one thing or another, or both

查看:2725
本文介绍了在正则表达式中,匹配一个或另一个,或两者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在正则表达式中,我需要知道如何匹配一个或另一个,或两者(按顺序)。但至少有一件事需要在那里。

In a regular expression, I need to know how to match one thing or another, or both (in order). But at least one of the things needs to be there.

例如,以下正则表达式

/^([0-9]+|\.[0-9]+)$/

将匹配

234

.56

但不是

234.56

以下正则表达式

/^([0-9]+)?(\.[0-9]+)?$/

将匹配上面所有三个字符串,但它也会匹配我们不想要的空字符串。

will match all three of the strings above, but it will also match the empty string, which we do not want.

I需要能匹配上面所有三个字符串的东西,但不是空字符串。有没有一种简单的方法呢?

I need something that will match all three of the strings above, but not the empty string. Is there an easy way to do that?

更新:

两个安德鲁的Justin的下面是我提供的简化示例的工作,但他们没有(除非我错了)为我希望解决的实际用例工作,所以我现在应该把它放进去。这是我正在使用的实际正则表达式:

Both Andrew's and Justin's below work for the simplified example I provided, but they don't (unless I'm mistaken) work for the actual use case that I was hoping to solve, so I should probably put that in now. Here's the actual regexp I'm using:

/^\s*-?0*(?:[0-9]+|[0-9]{1,3}(?:,[0-9]{3})+)(?:\.[0-9]*)?(\s*|[A-Za-z_]*)*$/

这将匹配

45
45.988
45,689
34,569,098,233
567,900.90
-9
-34 banana fries
0.56 points

但不匹配

.56

我需要要做到这一点。

推荐答案

完全通用的方法,给定正则表达式 / ^ A $ / / ^ B $ / 是:

The fully general method, given regexes /^A$/ and /^B$/ is:

/^(A|B|AB)$/

ie

/^([0-9]+|\.[0-9]+|[0-9]+\.[0-9]+)$/

注意其他人已使用您的示例结构进行简化。具体来说,他们(隐含地)将其分解,以拉出常见的 [0-9] * [0-9] + 左右两个因素。

Note the others have used the structure of your example to make a simplification. Specifically, they (implicitly) factorised it, to pull out the common [0-9]* and [0-9]+ factors on the left and right.

这适用于:


  • 交替的所有元素都在 [0-9] + 中结束,所以把它拉出来: / ^(| \。| [0-9] + \。)[0-9] + $ /

  • 现在我们有可能在交替中出现空字符串,所以使用重写它(即使用等价(| a | b)=(a | b)?): / ^(\。| [0-9] + \。)?[0-9] + $ /

  • 再次,使用公共后缀( \。这次)的替换: / ^((| [0-9] +)\。 )?[0-9] + $ /

  • 模式(| a +)是一样的as a * ,最后: / ^([0-9] * \。)?[0-9] + $ /

  • all the elements of the alternation end in [0-9]+, so pull that out: /^(|\.|[0-9]+\.)[0-9]+$/
  • Now we have the possibility of the empty string in the alternation, so rewrite it using ? (i.e. use the equivalence (|a|b) = (a|b)?): /^(\.|[0-9]+\.)?[0-9]+$/
  • Again, an alternation with a common suffix (\. this time): /^((|[0-9]+)\.)?[0-9]+$/
  • the pattern (|a+) is the same as a*, so, finally: /^([0-9]*\.)?[0-9]+$/

这篇关于在正则表达式中,匹配一个或另一个,或两者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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