简体   繁体   中英

Split a String, deleting some delimiters but keeping others

Ok, so my problem is that I want to be able to parse a string and split it, keeping some delimiters and deleting others.

Let's say my input string is 1.8.0a . I want to be able to put the string into an array, [1, 8, 0, a] . I've seen other SO questions , and the best answer is close to what I want. My current code is:

String[] array = s.split("[-._[?<=a[b[r]]]]");

The only problem is that my output is

[1, 8, 0]

EDIT:

Here's a few more examples:

Input: 1.18.0a

Output: [1, 18, 0]

Expected output: [1, 18, 0, a]

Input: 1.22.0r

Output: [1, 22, 0]

Expected output: [1, 22, 0, r]

Also, I used parenthesis,

String[] array = s.split("[-._(?<=a[b[r]])]");

Still to no avail.

If you just want to handle version strings like this, I personally would just walk through the string character by character, copying characters into a StringBuilder until I reached a delimiter, then convert the StringBuilder to a String and store it in the array. That would allow me to consider the switch from digits to letters as a "delimiter".

But then, I find regular expressions quite opaque. They're useful in some cases, but sometimes plain Java code, while more verbose, is simpler and easier to understand.

It looks like you want to split

  • on - . _
  • or between digit and alphabetic characters.

In that case you can try with

yourText.split("[-._]|(?<=[0-9])(?=[a-zA-Z])")

You can use the following regex:

String[] array = s.split("[-._]|(?=[abr])");

See Ideone Demo

Output:

[1, 18, 0, a]          //for input = "1.18.0a"

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