Richard
Richard

Reputation: 8935

Regex - Remove the final character

I have the following Regex

(?:(?:zero|one|two|three|four|five|six|seven|eight|nine|\[0-9‌​\])\s*){4,}

As you can see, it matches numbers with whitespace.

Question

How do I stop it from matching the final whitespace character?

For example:

1   2 3 4  5<whitespace> 

should rather be:

1   2 3 4  5

Upvotes: 1

Views: 52

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

The way you wrote the regex, trailing whitespaces will always be a part of a match, and there is no way to get rid of them. You need to rewrite the pattern repeating the number matching part inside a group that you need to assign the limiting quantifier with the min value decremented.

Schematically, it looks like

<NUMPATTERN>(?:\s+<NUMPATTERN>){3,}

See the regex demo.

In PCRE and Ruby, you may repeat capture group patterns with (?n) syntax (to shorten the pattern):

(zero|one|two|three|four|five|six|seven|eight|nine|[0-9])(?:\s+\g<1>){3,}

See the regex demo

Upvotes: 2

Related Questions