4

I have a string like this:

test_0001_suiteid_111_leavepolicy_employee

When I split this in java using regular expression like this:

_(?=.*_)

It shows ouptut like this:

test
0001 
suiteid
111
leavepolicy_employee

But if I use this string:

test_0001_suiteid_111_leavepolicy

It shows ouptut like this:

test
0001 
suiteid
111_leavepolicy

Can you please explain why this is happening. I want the output same as first output using a common regular expression.

3
  • 2
    It cannot be the same as you require at least 1 _ after the _ you split against. What are your requirements for splitting? BTW, have a look at this demo. Commented Sep 23, 2015 at 14:56
  • If there is a fixed number of key/value pairs in that string you should split on just _ (no regex needed) and limit the number of elements you want back. Commented Sep 23, 2015 at 15:01
  • thanks all for your suggestion. Commented Sep 28, 2015 at 11:07

2 Answers 2

2

Behaviour is as expected, which splits on underscore only if another underscore appears later in the input - due to the look ahead (?=.*_).

If instead you also want to split if the underscore appears after a digit, use this regex:

(?<=\d)_|_(?=.*_)

See live regex demo

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

Comments

1

You say you are doing that in Java. If you use String#split(), you can use the two-argument version and supply a number of elements you want to get back. I am assuming the number of key/value pairs in your string is fixed or you know it.

String string = "test_0001_suiteid_111_leavepolicy_employee";
String[] parts = string.split("_", 5);

That should give you a list of five elements:

test
0001
suiteid
111
leavepolicy_employee

Equally it will yield five elements if you put in test_0001_suiteid_111_leavepolicy.

3 Comments

Disclaimer: I needed to look up the Java syntax as I am not a Java guy, but the concept should be clear enough.
thanks @simbabque, i solve my problem using split method according to ur suggestion.
@noor I'm glad it helped. Please accept the answer by clicking the tick mark on the left so that others see which solution worked best for you. See How to Ask if you need help with that. Thanks.

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.