0

I have a String like below,

String str = "12 67 239 2 47 29";

Here i want to split the above string by using " 2 "

System.out.println(StringUtils.split(str, " 2 ")[0]);

I got a result, 1.

But i want the result like below,

12 67 239 2 

How can i do it guys, Please help me.

4
  • 2
    I think what you want is to get a substring of the string and not to split the string. You can easily do that by implementing a regular expression. It is best that you post the code that you have tried. Commented Oct 5, 2017 at 16:33
  • You are writting on console the first position of your array, not the whole array. Furthermore, I agree with Aradhna, you just don't want to split the string Commented Oct 5, 2017 at 16:36
  • @Aradhna why not to split, str.split("(?<=\\s2)\\s+")[0], split accepts a regex as it's first argument. Commented Oct 5, 2017 at 16:36
  • for matching this regex would be enough .*?\\b2\\b Commented Oct 5, 2017 at 16:38

1 Answer 1

1

Use the below regex to split the string on one or more spaces which exists next to 2.

str.split("(?<=\\s2)\\s+")[0]
  • (?<=\\s2) positive lookbehind which looks next to the <space>2

  • \\s+ matches one or more spaces.

  • Since the split will occur only on the matched characters, the above string should be splitted using the space which exists next to 2 as delimiter.

or

Remove all the characters which exists next to 2.

System.out.println(str.replaceFirst("(\\s2)\\s+.*", "\\1"));
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much @Avinash Raj. It's working fine. I have one doubt, in third point which you mentioned in answer, did this work for delimiter with prefix and suffix with white space right?
Could you please provide the reference (or) tutorial link for "Regular Expression" .
@kanna yep, but it would do split on the suffix whitespace. this site covers almost every regex regular-expressions.info/quickstart.html

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.