简体   繁体   中英

Split string in java based on integer delimeter

I'm trying to split a couple of strings based on the integer that's in the based, while still retaining the integer.

String theMessage = "1. First String. 2. Second String. 10. Tenth String. 20. Twentieth String.";
String delims = "(?<=(0*([0-9]{1,2}|100)))";
String[] questions = theMessage.split(delims);  
System.out.println(Arrays.toString(questions));

But it separates them as:

1. First String. 2 
 . Second String. 1 
1 
0 
 . Tenth String. 2 
0 \n
 . Twentieth String 

But I want them to be separated like this:

1. First String.
2. Second String.
10. Tenth String.
20. Twentieth String.

Basically I want each separated portion to be a different element in an array.

You can split on whitespace preceding your integers, resulting each group as an array element.

String s = "1. First String. 2. Second String. 10. Tenth String. 20. Twentieth String.";
String[] parts = s.split("\\s+(?=[0-9])");
System.out.println(Arrays.toString(parts));

See Live demo

Output

[1. First String., 2. Second String., 10. Tenth String., 20. Twentieth String.]

The following works so long as you can never have digits within the strings.

String numberedString = "1. First String. 2. Second String. 10. Tenth String. 20. Twentieth String.";
Pattern numberedStringPattern = Pattern.compile("([0-9]+)\\.([^0-9]+)");
Matcher numberedStringMatcher = numberedStringPattern.matcher(
        numberedString);

while(numberedStringMatcher.find()) {
    System.out.println("Found string "+numberedStringMatcher.group(
            1)+" with value \""+numberedStringMatcher.group(2)+"\"");
}

This code gives the output:

Found string 1 with value " First String. "
Found string 2 with value " Second String. "
Found string 10 with value " Tenth String. "
Found string 20 with value " Twentieth String."

So you will probably want to use trim() to remove the whitespace at the start and end of the returned String values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM