regex - Match filename with or without extension

1.5k views Asked by At

Need a regex pattern to match all of the following:

hello
hello.
hello.cc

I tried \b\w+\.?\w+?\b, but this doesn't match "hello." (the second string mentioned above).

2

There are 2 answers

0
Bohemian On BEST ANSWER

This is about as simple as I can get it:

\b\w+\.?\w*

See demo

3
bro On

The problem is that you enforce the word boundary \b after the dot, which doesn't match and the fact that you require at least one character after with \w+? (lazy matching!). Try this instead:

\b\w+\.?(\w+\b)?

https://regex101.com/r/lX1aE0/1

For more explanations about word boundaries, check this link
http://www.regular-expressions.info/wordboundaries.html