Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match string that starts with but does not include

Tags:

regex

I'm trying to match file paths that start with any string from a list. This is what I am using for that:

^/(dir1|dir2|dir3|tmp|dir4)/

I'm also trying to match all paths that start with /tmp/ but do not contain special after that.

This should match:

/tmp/subdir/filename.ext

But this should not:

/tmp/special/filename.ext

I can't seem to find a way to get this done. Any suggestions would be greatly appreciated.

like image 705
Bogdan Avatar asked Nov 05 '13 12:11

Bogdan


People also ask

How do you search for a regex pattern at the beginning of a string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.

How do you say does not contain in regex?

In order to match a line that does not contain something, use negative lookahead (described in Recipe 2.16). Notice that in this regular expression, a negative lookahead and a dot are repeated together using a noncapturing group.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .


1 Answers

Try ^(?i)/(dir1|dir2|dir3|tmp(?!\/(special))|dir4)/.*

(?i) = Case insesitivity this will match SpEcial, SPECial, SpEcIAL etc.

(?!\/(special)) = Negative lookahead for the '/special'

like image 161
Srb1313711 Avatar answered Oct 30 '22 04:10

Srb1313711