簡體   English   中英

JAVA REGEX:如何找到完全匹配的組?

[英]JAVA REGEX : How do I find the exact matching group?

碼:

String in = "text2";
Pattern pat = Pattern.compile("((?:text1))|((?:text2))");
Matcher mat = pat.matcher(in);
if(mat.find())
{
     //print the matching group number 
     //without any iteration
     //here the answer is group 2.
}

我的模式是((?:text1))|((?:text2)) ,在將“ text2”與我的模式匹配時,它給出了mat.group(1)作為EMPTY STRING和mat.group(2)作為text2

因此,我的輸入與模式中的匹配組編號2匹配。

我的問題是沒有任何迭代,有沒有辦法找到確切的匹配組?

給定一個正則表達式(group1)|(group2)|(group3)|...|(groupn) ,就不可能不經過至少(n-1)個組就知道哪個組與文本匹配,並檢查它是否捕獲了一些文本或為null

但是,可以通過調用Matcher.start(int group)減少String構建的開銷,並檢查返回的索引是否為非負數(大於或等於0)。


順便說一下,這是Oracle實現(版本8- Matcher.group(int group)Matcher.group(int group)的源代碼:

public String group(int group) {
    if (first < 0)
        throw new IllegalStateException("No match found");
    if (group < 0 || group > groupCount())
        throw new IndexOutOfBoundsException("No group " + group);
    if ((groups[group*2] == -1) || (groups[group*2+1] == -1))
        return null;
    return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();
}

Matcher.start(int group)相比,也是Oracle的實現版本8-b123:

public int start(int group) {
    if (first < 0)
        throw new IllegalStateException("No match available");
    if (group < 0 || group > groupCount())
        throw new IndexOutOfBoundsException("No group " + group);
    return groups[group * 2];
}

從理論上講,可以通過檢查O(log n)捕獲組來判斷哪個組與文本匹配。 您可以通過將組1的捕獲組添加到組(n div 2),將組(n div 2 +1)捕獲組添加到組n,來創建搜索樹。 這使您可以通過跟隨具有匹配項的分支來搜索與文本匹配的組。 但是,我建議不要這樣做,因為邏輯非常復雜且容易出錯(在添加較大的捕獲組之后,組號會發生變化,並且組數並不總是2的冪)。

不幸的是,這是不可能的。 我想,您可以針對像您的示例這樣的簡單案例進行修改,例如:

if (mat.find()) {
    int group = (mat.group(1) == null ? 2 : 1);
}

但這並不能給您帶來太大的好處,而且您總是必須至少對n個組進行n-1個(假設找到了匹配項)比較(注意,上面仍然是2組的1組檢查)。

如果您不想依賴組的順序,則可以使用命名捕獲組。 盡管這實際上並不能實現您的目標,但它確實為您提供了靈活的能力,使您能夠對正則表達式中的組進行重新排序,而不必修改代碼中的整數值以進行匹配。

暫無
暫無

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

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