开发者

java regex: (C identifier followed by __)

I'm looking for a way to match a C identifier followed by a double-underscore. But here's the thing: I need it to be non-greedy if the identifier ends in a series of underscores.

I almost got it with ^([_A-Za-z][_A-Za-z0-9]*?)__ but there's a tricky set of cases where the identifier can end in a series of underscores:

string          expected identifier
abcd0__         abcd0
abcd0___        abcd0_
abcd0____       abcd0__
abcd__0__       abcd
abcd___0__      abcd_
abcd____0__     abcd__

Is there a way I can modify the regex to produce the expected group match listed above?

Below is a test program which prints the incorrect output:

abcd0__ -> match is abcd0
abcd0___ -> match is abcd0
abcd0____ -> match is abcd0
abcd__0__ -> match is abcd
abcd___0__ -> match is abcd
abcd____0__ -> match is abcd

Regex3.java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex3 {
    final static private Pattern pattern = 
       Pattern.compile("^([_A-Za-z][_A-Za-z0-9]*?)__");

    static public void main(String[] args)
    {
        String[] items = {
                "abcd0__",
                "abcd0___",
                "abcd0____",
                "abcd__0__",
                "abcd开发者_Go百科___0__"
                "abcd____0__"
        };
        for (String item : items)
            test(item);
    }
    private static void test(String item) {
        Matcher m = pattern.matcher(item);
        if (m.find())
        {
            System.out.println(item+" -> match is "+m.group(1));
        }
        else
        {
            System.out.println(item+" -> no match");            
        }
    }
}


^[_A-Za-z](?:_?[A-Za-z0-9])*_*(?=__)

In JavaScript in the squarefree shell,

var re = /^[_A-Za-z](?:_?[A-Za-z0-9])*_*(?=__)/
var arr = ["abcd0__", "abcd0___", "abcd0____", "abcd__0__", "abcd___0__",
           "abcd____0__", "abcd", "abcd_"]
for (var i = 0; i < arr.length; i++) {
  print(arr[i] + " : " + re.exec(arr[i]));
}

produces

abcd0__ : abcd0
abcd0___ : abcd0_
abcd0____ : abcd0__
abcd__0__ : abcd
abcd___0__ : abcd_
abcd____0__ : abcd__
abcd : null
abcd_ : null


The Pattern ^([_A-Za-z][_A-Za-z0-9]*?_*)_{2}should match the identifier you would expect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜