鑑於你的正則表達式,我假設<signed_float>
確實不是支持科學記數法。
正則表達式匹配的浮子/雙到在Javadoc列出Double.valueOf(String)。
在這種情況下,regex是:
PREFIX Matching exact letters "PREFIX"
(?: Start optional section
\( Matching exact character "("
( Start content capture #1 <signed_float>
[+-]? Matches optional sign
(?: Start choice section
\d+\.?\d* Matches <digits> ["."] [<digits>]
| Choice separator
\.\d+ Matches "." <digits>
) End choice section
) End content capture #1
\) Matching exact character ")"
)? End optional section
= Matching exact character "="
(\S*) Capture #2 <Some_alpha_num_string>
或字符串:
"PREFIX(?:\\(([+-]?(?:\\d+\\.?\\d*|\\.\\d+))\\))?=(\\S*)"
測試一下:
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("<do nothing>");
else if (m.group(1) == null)
System.out.println("'" + m.group(2) + "'");
else
System.out.println(Double.parseDouble(m.group(1)) + ", '" + m.group(2) + "'");
}
輸出:
'fOo1234bar'
-1.23456, 'SomeString'
0.2, '1A2b3C'
<do nothing>
「*我如何使用它來提取這兩塊?*」捕獲組。 – user1803551