0

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.

Community
  • 1
  • 1
  • 1
    You'll have to give a few more examples to get a good answer. For example, what's the output for "1.18.0a" and for "1.8.10a"? – dcsohl May 26 '15 at 17:31
  • Also do bear in mind that the other question you linked to uses lookarounds, and the syntax has parentheses involved. You're missing the parentheses, so it's possible this is your problem. `(?<=x)` is a lookbehind but without the parentheses it's not going to do what you want. – dcsohl May 26 '15 at 17:36

3 Answers3

0

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.

Warren Dew
  • 8,790
  • 3
  • 30
  • 44
0

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])")
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

You can use the following regex:

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

See Ideone Demo

Output:

[1, 18, 0, a]          //for input = "1.18.0a"
karthik manchala
  • 13,492
  • 1
  • 31
  • 55