本文介绍了正则表达式匹配电话号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想匹配一个可以有字母和可选连字符的电话号码:

I want to match a phone number that can have letters and an optional hyphen:

  • 这是有效的:333-WELL
  • 这也是有效的:4URGENT
  • This is valid: 333-WELL
  • This is also valid: 4URGENT

换句话说,最多可以有一个连字符,但是如果没有连字符,则最多可以有七个0-9或A-Z字符.

In other words, there can be at most one hyphen but if there is no hyphen, there can be at most seven 0-9 or A-Z characters.

我不知道如何做和在正则表达式中使用"if语句".那有可能吗?

I dont know how to do and "if statement" in a regex. Is that even possible?

推荐答案

您正在寻找用竖线字符表示的交替运算符:|

You seek the alternation operator, indicated with pipe character: |

但是,您可能需要7个替代方法(每个连字符位置1个+不包含连字符1个),或者您可能需要在第3个字符和第4个字符之间使用连字符,并使用2个替代方法.

However, you may need either 7 alternatives (1 for each hyphen location + 1 for no hyphen), or you may require the hyphen between 3rd and 4th character and use 2 alternatives.

交替运算符的一种用法定义了两种选择,如:

One use of alternation operator defines two alternatives, as in:

({3,3}[0-9A-Za-z]-{4,4}[0-9A-Za-z]|{7,7}[0-9A-Za-z])

这篇关于正则表达式匹配电话号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-16 02:34