1

I have a string say, "1.0+20*30.2-4.0/10.1" which I want to split in such a way that I will have a string array say

strArr = {"1.0", "20", "30.2", "4.0",10.1}

I wrote the following code for this

public class StringSplitDemo {
public static void main(String[] args) {
    String str = "1.0+20*30.2-4.0/10.1";
    String[] strArr = (str.split("[\\+-/\\*]"));
    for(int i=0;i<strArr.length;i++)
      System.out.print(strArr[i]+" ");
  }
}

Rather than printing the expected output(by me) i.e 1.0 20 30.2 4.0 10.1 it prints

output: 1 0 20 30 2 4 0 10 1 

which seems to split the string also around "." even if I didn't include it in the regex pattern.

What I'm missing here? What is the right way to do this?

1
  • 1
    str.split("[-+/*]") Commented Oct 16, 2016 at 22:07

2 Answers 2

1

Use

String str = "1.0+20*30.2-4.0/10.1";
String[] strArr = str.split("[-+/*]");
System.out.print(Arrays.toString(strArr));

See the online Java demo

The [\\+-/\\*] character class matches more than just the 4 chars you defined, as - created a range between + and /.

enter image description here

You could fix the regex by escaping the hyphen, but the pattern looks much cleaner when you put the - at the start (or end) of the character class, where you do not have to escape it as there, the hyphen is treated as a literal -.

Sign up to request clarification or add additional context in comments.

2 Comments

You are right. It will be cleaner without using any escape symbol.
Thanks @Wiktor for your help;
0

The issue was in regex

So you need to escape + otherwise it will treat it as atleast once

String[] strArr = (str.split("[\\-/\\*\\+]"));

By the way escape symbol here is not required. It can simply be written as

String[] strArr = (str.split("[-/*+]"));

1 Comment

Inside a character class, only the - out of these 4 symbols needs to be escaped, and only when placed not in the final positions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.