Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a regex to exclude certain strings

Tags:

regex

I'm trying to get a regex that will match:

somefile_1.txt
somefile_2.txt
somefile_{anything}.txt

but not match:

somefile_16.txt

I tried

somefile_[^(16)].txt

with no luck (it includes even the "16" record)

like image 500
TheSoftwareJedi Avatar asked Nov 24 '08 16:11

TheSoftwareJedi


People also ask

How do you exclude words in regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

How do you exclude a string?

The most simple way to exclude lines with a string or syntax match is by using grep and the -v flag. The output will be the example. txt text file but excluding any line that contains a string match with “ThisWord”.

How do I remove a specific character from a string in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")


1 Answers

Some regex libraries allow lookahead:

somefile(?!16\.txt$).*?\.txt

Otherwise, you can still use multiple character classes:

somefile([^1].|1[^6]|.|.{3,})\.txt

or, to achieve maximum portability:

somefile([^1].|1[^6]|.|....*)\.txt

[^(16)] means: Match any character but braces, 1, and 6.

like image 110
phihag Avatar answered Oct 11 '22 03:10

phihag