Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

Given the following input string 3481.7.1071.html

I want to confirm that

  1. The string has 1 or more numbers followed by a period.
  2. The string ends in html.

Finally, I want to extract the left-most number (i.e. 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?

like image 798
johnstok Avatar asked Jan 24 '23 17:01

johnstok


1 Answers

You can just factor it out:

(\d+\.)(\d+\.)*html
like image 199
jpalecek Avatar answered Jan 29 '23 21:01

jpalecek