
您可以寻求正则表达式的帮助来解决此问题。考虑这样的代码:
String arr[] = {"12341234abc", "1234foo1234", "12121212", "111111111", "1a1212b123123c12341234d1234512345"};String regex = "(\d+?)";Pattern p = Pattern.compile(regex);for (String elem : arr) { boolean noMatchFound = true; Matcher matcher = p.matcher(elem); while (matcher.find()) { noMatchFound = false; System.out.println(elem + " got repeated: " + matcher.group(1)); } if (noMatchFound) { System.out.println(elem + " has no repeation"); }}输出:
说明:abc12341234abc got repeated: 12341234foo1234 has no repeation12121212 got repeated: 1212121212 got repeated: 12111111111 got repeated: 1111111111 got repeated: 1111111111 got repeated: 1111111111 got repeated: 11a1212b123123c12341234d1234512345 got repeated: 121a1212b123123c12341234d1234512345 got repeated: 1231a1212b123123c12341234d1234512345 got repeated: 12341a1212b123123c12341234d1234512345 got repeated: 12345
使用正则表达式的
(\d+?)地方
\d - means a numerical digit\d+ - means 1 or more occurrences of a digit\d+? - means reluctant (non-greedy) match of 1 OR more digits( and ) - to group the above regex into group # 1 - means back reference to group # 1(\d+?) - repeat the group # 1 immediately after group # 1
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)