简体   繁体   English

如何将重复模式与 Java 正则表达式匹配?

[英]How can I match a repeating pattern with Java regular expressions?

Given the following input string 3481.7.1071.html给定以下输入字符串3481.7.1071.html

I want to confirm that我想确认

  1. The string has 1 or more numbers followed by a period.该字符串有 1 个或多个数字,后跟一个句点。
  2. The string ends in html .字符串以html 结尾

Finally, I want to extract the left-most number (ie 3481).最后,我想提取最左边的数字(即 3481)。

My current regex is nearly there but I can't capture the correct group:我当前的正则表达式几乎就在那里,但我无法捕获正确的组:

final Pattern p = Pattern.compile("(\\d++\\.)+html");   
final Matcher m = p.matcher("3481.7.1071.html");
if (m.matches()) {
    final String corrected = m.group(1)+"html"; // WRONG! Gives 1071.html
}

How do I capture the first match?如何捕捉第一场比赛?

You can just factor it out:你可以把它分解出来:

(\d+\.)(\d+\.)*html
"^(\\d+)\\.(\\d+\\.)*html$"
groovy:000> p = java.util.regex.Pattern.compile("(\\d+).*") 
===> (\d+).*
groovy:000> m = p.matcher("3481.7.1071.html")
===> java.util.regex.Matcher[pattern=(\d+).* region=0,16 lastmatch=]
groovy:000> m.find()
===> true
groovy:000> m.group(1)+".html"
===> 3481.html
groovy:000> 

Yes, you can.是的你可以。

If 123.html and 1.23html and are valid , use this :如果123.html1.23html有效,请使用

^(?:(\d+)\.).*?html$

If 123.html is invalid but 1.23html valid , use this :如果123.html无效1.23html有效,请使用

^(?:(\d+)\.(?!h)).*?html$

If 123.html and 1.23html are invalid but only 1.23.html valid , use this :如果123.html1.23html无效但只有1.23.html有效,请使用

^(?:(\d+)\.).*?\.html$

Java style: "(\\d+)\\..*?\\.html$" Java 样式: "(\\d+)\\..*?\\.html$"

This will 1) grab the first group of consecutive digits, 2) require a dot after words, 3) jump over everything except 3) the literal string '.html'.这将 1) 获取第一组连续数字,2) 在单词之后需要一个点,3) 跳过除 3) 文字字符串“.html”之外的所有内容。

If you mean "one or more [ groups ] of numbers followed by a period" then this is more along the lines of your requirements.如果您的意思是“一个或多个 [] 数字后跟一个句点”,那么这更符合您的要求。

"(\\d+)(?:\\.\\d+)*\\.html$"

This way you get a number and not the dot.这样你得到一个数字而不是点。 And none of the other patterns need to be captured, so they are not.并且不需要捕获任何其他模式,所以它们不是。

jpalecek's solution fails; jpalecek 的解决方案失败了; it captures the rightmost number.它捕获最右边的数字。 The original poster was a lot closer, but he got the right-most number.原始海报更接近,但他得到了最右边的数字。 To get the left-most number, ignore anything after the first dot:要获得最左边的数字,请忽略第一个点之后的任何内容:

[^\d]*(\d+)\..*html

[^\d]* ignores everything before the left-most number (so X1.html captures number 1) (\d+). [^\d]* 忽略最左边数字之前的所有内容(因此 X1.html 捕获数字 1)(\d+)。 captures the first digits, if they are followed by a dot.捕获第一个数字,如果它们后跟一个点。 .* ignores everything between the dot and the final html. .* 忽略点和最终 html 之间的所有内容。

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

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