簡體   English   中英

Java Regex不一致的組

[英]Java Regex inconsistent groups

請參考以下關於SO的問題:

Java:正則表達式不匹配

我的正則表達式組不一致。 我的代碼如下:

public class RegexTest {

    public static void main(String[] args) {

        // final String VALUES_REGEX = "^\\{([0-9a-zA-Z\\-\\_\\.]+)(?:,\\s*([0-9a-zA-Z\\-\\_\\.]*))*\\}$";
        final String VALUES_REGEX = "\\{([\\w.-]+)(?:, *([\\w.-]+))*\\}";

        final Pattern REGEX_PATTERN = Pattern.compile(VALUES_REGEX);
        final String values = "{df1_apx.fhh.irtrs.d.rrr, ffd1-afp.farr.d.rrr.asgd, ffd2-afp.farr.d.rrr.asgd}";
        final Matcher matcher = REGEX_PATTERN.matcher(values);
        if (null != values && matcher.matches()) {
            // for (int index=1; index<=matcher.groupCount(); ++index) {
            // System.out.println(matcher.group(index));
            // }

            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }

    }
}

我嘗試了以下組合:

A)正則表達式為“ ^ \\ {([0-9a-zA-Z \\-\\ _ \\。] +)(?:,\\ s *([0-9a-zA-Z \\-\\ _ \\。] ) ) \\} $”,然后使用groupCount()進行迭代。 結果:

df1_apx.fhh.irtrs.d.rrr

ffd2-afp.farr.d.rrr.asgd

B)正則表達式為^ \\ {([0-9a-zA-Z \\-\\ _ \\。] +)(?:,\\ s *([0-9a-zA-Z \\-\\ _ \\。] )) \\} $”並使用matcher.find()。結果:無結果。

C)正則表達式為“ \\ {([\\ w .-] +)(?:, ([\\ w .-] +)) \\}”,然后使用groupCount()進行迭代。 結果:

df1_apx.fhh.irtrs.d.rrr

ffd2-afp.farr.d.rrr.asgd

D)正則表達式為“ \\ {([\\ w .-] +)(?:, ([\\ w .-] +)) \\}”,並使用matcher.find()。 結果:無結果。

我從來沒有得到一致的團體。 這里的預期結果是:

df1_apx.fhh.irtrs.d.rrr

ffd1-afp.farr.d.rrr.asgd

ffd2-afp.farr.d.rrr.asgd

請讓我知道,我該如何實現。

(?<=[{,])\s*(.*?)(?=,|})

您可以簡單地使用它並捕獲捕獲。請參閱演示。

https://regex101.com/r/sJ9gM7/33

當您有(#something)* ,正則表達式引擎只會記住最后一個組。您不會以這種方式獲得所有組。

問題是您試圖同時做兩件事:

  • 您要驗證字符串格式
  • 您要提取每個項目(項目數量未知)

因此,不可能使用matchs方法,因為當您重復相同的捕獲組時,以前的捕獲將被最后一個捕獲覆蓋。

一種可能的方法是使用find方法獲得每個項目,並使用連續性錨\\G檢查格式。 \\G確保當前匹配項立即跟在字符串的上一個或開頭之后:

(?:\\G(?!\\A),\\s*|\\A\\{)([\\w.-]+)(}\\z)?

圖案細節:

(?:                  # two possible begins:
    \\G(?!\\A),\\s*  # contiguous to a previous match
                     # (but not at the start of the string)
  |                  # OR
    \\A\\{           # the start of the string
)
([\\w.-]+)           # an item in the capture group 1
(}\\z)?              # the optional capture group 2 to check
                     # that the end of the string has been reached

因此,要從頭到尾檢查字符串的格式,您需要測試的是最后一個匹配項是否存在捕獲組2。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM