chris n
chris n

Reputation: 81

RegEx for a string to NOT contain two different strings

Ok you gurus out there who know Regex!

How do you use reg ex to search a string to make sure it doesn't contain either of two different strings.

Example: Say i want to make sure "FileNTile" doesnt contain File or Tile

Thanks

cnorr

Upvotes: 8

Views: 6844

Answers (2)

bobince
bobince

Reputation: 536547

^((?!File|Tile).)*$

This is unlikely to be a good idea though. Almost every programming environment will have a clearer and more efficient approach with string matching. (eg Python: if 'File' not in s and 'Tile' not in s)

Also not all regex implementations have lookahead. eg. it's not reliable in JavaScript. And there may be issues with newlines depending on mode (multiline, dotall flags).

Upvotes: 12

Peter
Peter

Reputation: 132307

It depends on the language. Easiest way (conceptually): search for both, and make sure both fail to match. In Ruby:

s = "FileNTile"
(s !~ /File/) and (s !~ /Tile)  # true if s is free of files and tiles.

Upvotes: 0

Related Questions