I have to parse a Java String into 3 separate cases:
If it has the form "PREFIX()=", I need to extract into one (Double) variable, into another (String) variable and ignore the rest.
Otherwise, if it has the form "PREFIX=", I save and set the Double to some default (say 0.0)
Otherwise I do nothing
So I guess the regex for #1 and #2 would be PREFIX[\(]?[-]?[0-9]*\.?[0-9]*[\)]?=\S*, but how do I use it to extract the two pieces?
BTW, I don't need to worry about the float being expressed in the scientific ("%e") notation
UPDATE: A bit of clarification: PREFIX is a fixed string. So examples of valid strings would be:
PREFIX=fOo1234bar -- here I need to extract fOo1234bar
PREFIX(-1.23456)=SomeString -- here I need to extract -1.23456 and SomeString
PREFIX(0.20)=1A2b3C -- here I need to extract 0.20 and 1A2b3C
解决方案
Given your regex, I'll assume that does not support scientific notation.
Regex for matching a float/double to listed in the javadoc for Double.valueOf(String).
In that case, the regex would be:
PREFIX Matching exact letters "PREFIX"
(?: Start optional section
\( Matching exact character "("
( Start content capture #1
[+-]? Matches optional sign
(?: Start choice section
\d+\.?\d* Matches ["."] []
| Choice separator
\.\d+ Matches "."
) End choice section
) End content capture #1
\) Matching exact character ")"
)? End optional section
= Matching exact character "="
(\S*) Capture #2
Or as a string:
"PREFIX(?:\\(([+-]?(?:\\d+\\.?\\d*|\\.\\d+))\\))?=(\\S*)"
Let's test it:
public static void main(String[] args) {
test("PREFIX=fOo1234bar");
test("PREFIX(-1.23456)=SomeString");
test("PREFIX(0.20)=1A2b3C");
test("sadfsahlhjladf");
}
private static void test(String text) {
Pattern p = Pattern.compile("PREFIX(?:\\(([+-]?(?:\\d+\\.?\\d*|\\.\\d+))\\))?=(\\S*)");
Matcher m = p.matcher(text);
if (! m.matches())
System.out.println("");
else if (m.group(1) == null)
System.out.println("'" + m.group(2) + "'");
else
System.out.println(Double.parseDouble(m.group(1)) + ", '" + m.group(2) + "'");
}
Output:
'fOo1234bar'
-1.23456, 'SomeString'
0.2, '1A2b3C'