How to substring this String

2019-06-28 02:03发布

I want to get 4 parts of this string

String string = "10 trillion 896 billion 45 million 56873";

The 4 parts I need are "10 trillion" "896 billion" "45 million" and "56873".

What I did was to remove all spaces and then substring it, but I get confused about the indexes. I saw many questions but could not understand my problem.

Sorry I don't have any code

I couldn't run because I didn't know that was right.

7条回答
劫难
2楼-- · 2019-06-28 02:42

You can use this regex:

\d+(?: (?:tri|bi|mi)llion)?

It first matches a bunch of digits \d+, and then optionally (?:...)?, we match either trillion, billion, or million (?:tri|bi|mi)llion.

enter image description here

To use this regex,

Matcher m = Pattern.compile("\\d+(?: (?:tri|bi|mi)llion)?").matcher(string);
while (m.find()) {
    System.out.println(m.group());
}
查看更多
登录 后发表回答