RegExp multi-valued match character always ends

Hi everyone, I am starting to start with stackoverflow.

If I have any errors in the question of this question, hope for me. :)

If my test string is 'One\nTwo\n\nFour',

I am using RegExp /(.)*\n/in JavaScript,

will match 'One\nTwo\n\n'not 'One\n', 'Two\n' and '\n'pending.

And I want to get the result 'One', 'Two', '' and 'Four'.


Thanks very much @Dalorzo for the answer.

'One\nTwo\n\nFour'.split(/\n/g) //outputs ["One", "Two", "", "Four"]

+4
source share
2 answers

Maybe a split could be better for the same goal? on the

With Regex :

'One\nTwo\n\nFour'.split(/\n/) //outputs ["One", "Two", "", "Four"]

or without regex , for example:

'One\nTwo\n\nFour'.split('\n') //outputs ["One", "Two", "", "Four"]
+4
source
(.*?)(?:\n|$)

. .

https://regex101.com/r/vD5iH9/30

var re = /(.*?)(?:\n|$)/g;
var str = 'One\nTwo\n\nFour';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
+3

All Articles