简体   繁体   English

如何使这种常规表达与Java-android?

[英]how to make this regular excepression work with java - android?

How to use this with String.matches(...........) 如何与String.matches(...........)

^\\s*(?:\\+?(\\d{1,3}))?[-. (]*(\\d{3})[-. )]*(\\d{3})[-. ]*(\\d{4})(?: *x(\\d+))?\\s*$

It would match the following examples and much more: 它将匹配以下示例以及更多示例:

18005551234     
1 800 555 1234    
+1 800 555-1234

+86 800 555 1234    
1-800-555-1234    
1 (800) 555-1234    
(800)555-1234    
(800) 555-1234    
(800)5551234
800-555-1234
800.555.1234
800 555 1234x5678    
8005551234 x5678    
1    800    555-1234    
1----800----555-1234

First, you need to escape the first + in your pattern. 首先,您需要转义模式中的第一个+

Then, make delimiters optional and allow more than one in consequence to match all variants like 1 (800) 555-1234 , (800) 555-1234 , and 18005551234 . 然后,使定界符为可选,并允许多个结果匹配所有变体,例如1 (800) 555-1234(800) 555-123418005551234

The regex would be: 正则表达式为:

^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: ?x(\d+))?\s*$

Demo: https://regex101.com/r/pV4hL9/1 演示: https : //regex101.com/r/pV4hL9/1

Finally, in Java, escape backslashes with backslashes: https://ideone.com/L6bNA9 最后,在Java中,用反斜杠转义反斜杠: https : //ideone.com/L6bNA9

You could use: libphonenumber 您可以使用: libphonenumber
And if you're developing for android 4.0 (Ice Cream Sandwich) or later it is built in within the android framework. 而且,如果您要开发的是android 4.0(冰淇淋三明治)或更高版本,则它是在android框架中内置的。

(This was mentioned before by someone else, but they removed the answer) (其他人之前曾提到过,但他们删除了答案)

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

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