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
Varun Muralidharan
1411 gold badge2 silver badges12 bronze badges
2 Answers 2
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
VisioN
146k35 gold badges287 silver badges291 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Varun Muralidharan
what if I wanted till the second '&', then what will change in the regex code?
Varun Muralidharan
ok then it would be this "example&ABC56748393&this&is&a&sample&string".split(/ABC.*?&.*?&/)
Mattias Buelens
Alternatively, with less repetition:
/ABC(?:.*?&){2}/. The (?:) just wraps it in a non-capturing group, so it can be treated as a single entity.Just use non greedy match, by placing a ? after the * or +:
<string>.split(/<constant_word>.*?&/)
answered Jan 17, 2013 at 19:46
ATOzTOA
36.1k23 gold badges101 silver badges119 bronze badges
Comments
lang-js