atapaka
atapaka

Reputation: 1360

Regexp match space or not

How would I match?

first second

first_second

firstsecond

first[\s|_]second

matches the first two but how to match the last one as well?

Upvotes: 0

Views: 995

Answers (1)

Sebastian Proske
Sebastian Proske

Reputation: 8413

You can use the ?-quantifier, matching a pattern 0 or 1 times. Please do also note, that | loses it's metacharacter function inside a charcater class, there is no need for an alternation inside a character class at all (as it already matches for one of the characters listed).

So your final regex is first[\s_]?second

If you only want to match spaces (and not tab or linebreak or any other kind of whitespace), just use first[ _]?second

Upvotes: 5

Related Questions