java float正则表达式,Java:如何使用正则表达式将字符串分成部分?

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'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值