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___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,
produces