Java正则表达式:重复组? [英] Java Regex: repetitive groups?

查看:92
本文介绍了Java正则表达式:重复组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java Regex中定义重复组?

How can I define repetitive groups in Java Regex?

让我们说一个2位数的数字[0-9] {2}多次用分隔,

Lets say a 2digit number [0-9]{2} multiple times separates by ,

12,34,98,11

这是唯一的机会吗?

我想验证并提取.

推荐答案

最简单的方法是使用两步式解决方案:1)首先,验证字符串,然后2)用您选择的定界符分割字符串:

The simplest way is to use a two-step solution: 1) first, validate the string, then 2) split the string with the delimiter of your choice:

String[] chunks = null;
if (s.matches("\\d{2}(?:,\\d{2})*")) {
    chunks = s.split(Pattern.quote(","));
    System.out.println(Arrays.toString(chunks)); // => [12, 34, 98, 11]
}

在这里, s.matches("\\ d {2}(?:,\\ d {2})*")匹配以两位数字开头并包含0的整个字符串或多次出现和末尾两位数字,然后 s.split(Pattern.quote(,"))用逗号分隔字符串.请注意,由于该方法需要完整的字符串匹配,因此不需要 ^ $ matches()内带有模式的锚点.

Here, s.matches("\\d{2}(?:,\\d{2})*") matches the whole string that starts with two digits and then contains 0 or more occurrences of , and two digits to the end, and then s.split(Pattern.quote(",")) splits the string with a comma. Note you do not need ^ and $ anchors with a pattern inside matches() since the method requires a full string match.

如果您必须使用单个正则表达式进行此操作,则可以使用多个匹配项,这些匹配项锚定在字符串的开头和每个成功的先前匹配项的结尾,前提是在字符串开头检查字符串是成功的:

If you have to do that with a single regex, you may use multiple matches anchored to the start of string and end of each successful preceding match, only if the string check at the start of the string is a success:

(?:\G(?!^),|^(?=\d{2}(?:,\d{2})*$))(\d{2})

请参见 regex演示.

详细信息

  • (?:\ G(?!^),| ^(?= \ d {2}(?:,\ d {2})* $))-前面的结尾成功匹配,然后是(请参阅 \ G(?!^),)或( | )字符串开头( ^),后跟两位数字,然后是的0个或多个序列,以及字符串末尾的两位数字(请参见 \ d {2}(?:,\ d {2})* $ )
  • (\ d {2})-第1组:两位数字
  • (?:\G(?!^),|^(?=\d{2}(?:,\d{2})*$)) - end of the preceding successful match and then a , (see \G(?!^),) or (|) start of string (^) that is followed with two digits and then 0 or more sequences of a , and two digits to the end of the string (see \d{2}(?:,\d{2})*$)
  • (\d{2}) - Group 1: two digits

Java演示:

String s = "12,34,98,11";
Pattern p = Pattern.compile("(?:\\G(?!^),|^(?=\\d{2}(?:,\\d{2})*$))(\\d{2})");
Matcher m = p.matcher(s);
List<String> results = new ArrayList<>();
while(m.find()) {
    results.add(m.group(1));
}
System.out.println(results); 
// => [12, 34, 98, 11]

这篇关于Java正则表达式:重复组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆