How do I use Java regex to find all repeated character sequences in a string?
•
Java
Use Java and regex to parse a random string to find repeated sequences
Consider string:
aaabbaaacccbb
I want to find a regular expression that can find all matches in the above string:
aaabbaaacccbb ^^^ ^^^ aaabbaaacccbb ^^ ^^
What is a regex expression that will check any repeated character sequence of the string and return the group of these repeated characters so that group 1 = AAA and group 2 = BB Also note that I used a sample string, but any duplicate characters are valid: ronronjoejoe
Solution
Do it in this way.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main(String[] args) { String s = "aaabbaaacccbb"; find(s); String s1 = "RonRonRonJoeJoe ....,"; find(s1); System.err.println("---"); String s2 = "RonBobRonJoe"; find(s2); } private static void find(String s) { Matcher m = Pattern.compile("(.+)\\1+").matcher(s); while (m.find()) { System.err.println(m.group()); } } }
OUTPUT:
aaa bb aaa ccc bb RonRonRon JoeJoe ....,---
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码