Rad*_*Rad 1 java regex pattern-matching
我正在考虑在字符串中获取所有唯一重复的最佳方法,并按长度和重复频率(数字)对它们进行排序
我开始使用此代码
public static void main(String[] args)
{
String s = "AAAABBBBAAAANNNNAAAABBBBNNNBBBBAAAA";
Matcher m = Pattern.compile("(\\S{2,})(?=.*?\\1)").matcher(s);
while (m.find())
{
for (int i = 1; i <= m.groupCount(); i++)
{
System.out.println(m.group(i));
}
}
}
Run Code Online (Sandbox Code Playgroud)
并希望得到一些有这样的输出的建议:
AAAA 4 1,9,17,33等
其中4 =重复次数,1,9,17,33个位置
我感谢您的帮助
首先,你的模式不会给你你想要的东西.你应该改变你的正则表达式: -
"(\\S)\\1+"
Run Code Online (Sandbox Code Playgroud)
重复单个字符.
现在要获取重复的位置和数量,您可以维护一个Map<String, List<Integer>>,以存储每次重复的位置.
此外,你不需要for在里面循环while.while循环足以迭代所有模式.
这是您修改后的代码: -
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
String s = "AAAABBBBAAAANNNNAAAABBBBNNNBBBBAAAA";
Matcher m = Pattern.compile("(\\S)\\1+").matcher(s);
while (m.find())
{
String str = m.group();
int loc = m.start();
// Check whether the pattern is present in the map.
// If yes, get the list, and add the location to it.
// If not, create a new list. Add the location to it.
// And add new entry in map.
if (map.containsKey(str)) {
map.get(str).add(loc);
} else {
List<Integer> locList = new ArrayList<Integer>();
locList.add(loc);
map.put(str, locList);
}
}
System.out.println(map);
Run Code Online (Sandbox Code Playgroud)
输出: -
{AAAA=[0, 8, 16, 31], BBBB=[4, 20, 27], NNNN=[12], NNN=[24]}
Run Code Online (Sandbox Code Playgroud)