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"]

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"]
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>.*?&/)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.