5

Let's say I have a generalized string

"...&<constant_word>+<random_words_with_random_length>&...&...&..."

I would want to split the string using

"<constant_word>+<random_words_with_random_length>&"

for which I tried RegEx split like

<string>.split(/<constant_word>.*&/)

This RegEx splits till the last '&' unfortunately i.e.

"<constant_word>+<random_words_with_random_length>&...&...&"

What would be the RegEx code if I wanted it to split when it gets the first '&'?

example for a string split like

"example&ABC56748393&this&is&a&sample&string".split(/ABC.*&/)

gives me

["example&","string"]

while what I want is..

["example&","this&is&a&sample&string"]
asked Jan 17, 2013 at 19:44

2 Answers 2

5

You may change the greediness with a question mark ?:

"example&ABC56748393&this&is&a&sample&string".split(/&ABC.*?&/);
// ["example", "this&is&a&sample&string"]
answered Jan 17, 2013 at 19:45
Sign up to request clarification or add additional context in comments.

3 Comments

what if I wanted till the second '&', then what will change in the regex code?
ok then it would be this "example&ABC56748393&this&is&a&sample&string".split(/ABC.*?&.*?&/)
Alternatively, with less repetition: /ABC(?:.*?&){2}/. The (?:) just wraps it in a non-capturing group, so it can be treated as a single entity.
2

Just use non greedy match, by placing a ? after the * or +:

<string>.split(/<constant_word>.*?&/)
answered Jan 17, 2013 at 19:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.