Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expressions: Matching strings starting with dot (.)?

Tags:

regex

I am a complete Reg-exp noob, so please bear with me. Tried to google this, but haven't found it yet.

What would be an appropriate way of writing a Regular expression matching files starting with a dot, such as .buildpath or .htaccess?

Thanks a lot!

like image 537
Industrial Avatar asked Jan 09 '11 18:01

Industrial


Video Answer


3 Answers

In most regex languages, ^\. or ^[.] will match a leading dot.

like image 163
ephemient Avatar answered Sep 22 '22 10:09

ephemient


The ^ matches the beginning of a string in most languages. This will match a leading .. You need to add your filename expression to it.

^\.

Likewise, $ will match the end of a string.

like image 31
jasonbar Avatar answered Sep 26 '22 10:09

jasonbar


You may need to substitute the \ for the respective language escape character. However, under Powershell the Regex I use is: ^(\.)+\/

Test case:

"../NameOfFile.txt" -match '^(\\.)+\\\/'

works, while

"_./NameOfFile.txt" -match '^(\\.)+\\\/'

does not.

Naturally, you may ask, well what is happening here?

The (\\.) searches for the literal . followed by a +, which matches the previous character at least once or more times.

Finally, the \\\/ ensures that it conforms to a Window file path.

like image 20
Porky Avatar answered Sep 25 '22 10:09

Porky