Husky
Husky

Reputation: 542

Multi matches character in RegExp alway end at last one

Hello everyone, I'm a stackoverflow novice.

If I have any wrong about asking this question, hope to redress me. :)

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

I use the RegExp /(.)*\n/ in JavaScript,

will match 'One\nTwo\n\n' not 'One\n', 'Two\n' and '\n' in my expectation.

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


Very thanks @Dalorzo's answer.

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

Upvotes: 4

Views: 47

Answers (2)

Dalorzo
Dalorzo

Reputation: 20014

Maybe better could be a split to achieve the same goal? by

With Regex:

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

or without Regex like:

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

Upvotes: 4

vks
vks

Reputation: 67968

(.*?)(?:\n|$)

Make your greedy search non greedy.See demo.

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.
}

Upvotes: 3

Related Questions