Reputation: 141
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"]
Upvotes: 5
Views: 11360
Reputation: 35950
Just use non greedy match, by placing a ?
after the *
or +
:
<string>.split(/<constant_word>.*?&/)
Upvotes: 2
Reputation: 145378
You may change the greediness with a question mark ?
:
"example&ABC56748393&this&is&a&sample&string".split(/&ABC.*?&/);
// ["example", "this&is&a&sample&string"]
Upvotes: 5