Week 95 — How can one find all ways a `String` matches a given regex?

Question of the Week #95
How can one find all sways a String matches a given regex?
1 Reply
Eric McIntyre
Eric McIntyre2mo ago
The Pattern class can be used to for regex matching. To create a Pattern from a String containing the regex, the Pattern.compile method can be used.
Pattern myRegex = Pattern.compile("(\\d+)\\.(\\d+)");//regex matching numbers with a decimal point
Pattern myRegex = Pattern.compile("(\\d+)\\.(\\d+)");//regex matching numbers with a decimal point
With a Pattern, it's possible to obtain a Matcher matching the pattern against a given String. The matches() method of that Matcher can then be used to check whether the String matches the given regex:
Matcher matcher = myRegex.matcher("123.45");
boolean matches = matcher.matches();//true
String beforeDecimalPoint = matcher.group(1);//123
String afterDecimalPoint = matcher.group(2);//45
Matcher matcher = myRegex.matcher("123.45");
boolean matches = matcher.matches();//true
String beforeDecimalPoint = matcher.group(1);//123
String afterDecimalPoint = matcher.group(2);//45
Instead of matching the whole String, it's also possible to find matches of the pattern within a given String using Matcher#find. This method returns true if a match has been found.
Matcher matcher = myRegex.matcher("Both 1.23 and 45.67 will be found");
while(matcher.find()){
System.out.println("found number: " + matcher.group() + " from position " + matcher.start() + " to position " + matcher.end());
System.out.println("before decimal point: " + matcher.group(1));
System.out.println("after decimal point: " + matcher.group(2));
}
Matcher matcher = myRegex.matcher("Both 1.23 and 45.67 will be found");
while(matcher.find()){
System.out.println("found number: " + matcher.group() + " from position " + matcher.start() + " to position " + matcher.end());
System.out.println("before decimal point: " + matcher.group(1));
System.out.println("after decimal point: " + matcher.group(2));
}
The above code prints the following:
found number: 1.23 from position 5 to position 9
before decimal point: 1
after decimal point: 23
found number: 45.67 from position 14 to position 19
before decimal point: 45
after decimal point: 67
found number: 1.23 from position 5 to position 9
before decimal point: 1
after decimal point: 23
found number: 45.67 from position 14 to position 19
before decimal point: 45
after decimal point: 67
📖 Sample answer from dan1st
Want results from more Discord servers?
Add your server