The next time you need a regex explanation, you can use the following service explain.plfrom Rick Mesham:
Regex: [^,]*|.+(,).+
NODE EXPLANATION
--------------------------------------------------------------------------------
[^,]* any character except: ',' (0 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
.+ any character except \n (1 or more times
(matching the most amount possible))
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
, ','
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
.+ any character except \n (1 or more times
(matching the most amount possible))
Regex: (\()?\d+(?(1)\))
NODE EXPLANATION
( group and capture to \1 (optional
(matching the most amount possible)):
\( '('
)? end of \1 (NOTE: because you're using a
quantifier on this capture, only the LAST
repetition of the captured pattern will be
stored in \1)
\d+ digits (0-9) (1 or more times (matching
the most amount possible))
(?(1) if back-reference \1 matched, then:
\) ')'
| else:
succeed
) end of conditional on \1
References
JAVA ! :
\d+|\(\d+\)
. , .
import java.util.regex.*;
Pattern p = Pattern.compile("[^,]*|.+(,).+");
String[] tests = {
"",
"abc",
",abc",
"abc,",
"ab,c",
"ab,c,",
",",
",,",
",,,",
};
for (String test : tests) {
Matcher m = p.matcher(test);
System.out.format("[%s] is %s %n", test,
!m.matches() ? "not a match"
: m.group(1) != null
? "a match with separating comma"
: "a match with no commas"
);
}
, ( Java):
Pattern p = Pattern.compile("\\d+|(\\()\\d+\\)");
String[] tests = {
"",
"0",
"(0)",
"007",
"(007)",
"(007",
"007)",
"-1",
};
for (String test : tests) {
Matcher m = p.matcher(test);
System.out.format("[%s] is %s %n", test,
!m.matches() ? "not a match"
: m.group(1) != null
? "a match with surrounding parenthesis"
: "a match without parenthesis"
);
}
, , , ( \1 ).