davymartu davymartu - 1 year ago 62
Javascript Question

Find all char excluding group at the end with regexp

I have this string:

this is a test

at the end of this string I have a space and the new line.
I want to extract (for counting) all space group in the string witout the last space.
With my simple regex


I obtain these groups:


I want to exclude from group the forth space because i want to get only 3 groups if the string end with space.
What is the correct regexp?

Answer Source

Depending on the regex flavor, you can use two approaches.

If atomic groups/possessive quantifiers are not supported, use a lookahead solution like this:


See the regex demo

The main point is that we only match a whitespace that is not followed with 0+ other whitespace symbols followed with an end of string (the check if performed with the (?!\s*$) lookahead).

Else, use


See another demo. An equivalent expression with an atomic groups is (?>\s+)(?!$).

Here, we check for the end of string position ONLY after grabbing all whitespaces without backtracking into the \s++ pattern (so, if after the last space there is an end of string, the whole match is failed).

Also, it is possible to emulate an atomic group in JavaScript with the help of capturing inside the positive lookahead and then using a backreference like


However, this pattern is costly in terms of performance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download