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"]
You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.
split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
To do this: Convert the number to a string. Call the split() method on the string to convert it into an array of stringified digits. Call the map() method on this array to convert each string to a number.
You may change the greediness with a question mark ?
:
"example&ABC56748393&this&is&a&sample&string".split(/&ABC.*?&/);
// ["example", "this&is&a&sample&string"]
Just use non greedy match, by placing a ?
after the *
or +
:
<string>.split(/<constant_word>.*?&/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With