简体   繁体   English

正则表达式-查找多个匹配项

[英]Regex - Find multiple matches

I have following 1010159552597 and I would like to find the numbers that start with 10, followed by 1 or 0 and ending with 7 digits. 我遵循1010159552597 ,我想找到以10开头,后跟1或0并以7位结尾的数字。 I use following RegEx to search 我使用以下RegEx进行搜索

(10[01][0-9]{7})

Following result is given: 1010159552 给出以下结果: 1010159552

But I also would have expected the following: 1015955259 但我也期望以下几点: 1015955259

How can I manage to get both results? 我怎样才能获得两个结果?

Thanks 谢谢

Regular expressions consume characters and don't go back over previous matches. 正则表达式使用字符,并且不会回退到先前的匹配项。 A way around this is to use zero-length assertions (see code below) to capture what you want. 一种解决方法是使用零长度断言(请参见下面的代码)来捕获您想要的内容。

Code

See regex in use here 查看正则表达式在这里使用

(?=(10[01]\d{7}))

Results are in capture group 1: 结果在捕获组1中:

  • 1010159552
  • 1015955259

Explanation 说明

  • (?=(10[01]\\d{7})) Positive lookahead ensuring what follows matches (?=(10[01]\\d{7}))正向前瞻确保后面的内容匹配
    • (10[01]\\d{7}) Capture your original expression into capture group 1 (10[01]\\d{7})将原始表达式捕获到捕获组1中

You're right in that your expectation does match your regex, however, it will try to find the first instance of that match. 您的期望确实与您的正则表达式匹配是正确的,但是,它将尝试查找该匹配的第一个实例。

In your case the first term is: 在您的情况下,第一项是:

10 - 1 - 0159552 10-1159552

so this is the solution given. 所以这是给出的解决方案。

Since your results are overlapping, you might want to check out this article. 由于您的结果是重叠的,因此您可能需要查看本文。

Overlapping matches in Regex 正则表达式中的重叠匹配

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

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