Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matching a line that doesn't contain specific text with regular expressions

Tags:

regex

I want to do the following with regular expressions but not sure how to do it. I want it to match one two when one two is the beginning of the line unless the string contains three anywhere after one two.

like image 937
Jared Avatar asked Jan 12 '09 20:01

Jared


People also ask

How do you match a blank line in regex?

The most portable regex would be ^[ \t\n]*$ to match an empty string (note that you would need to replace \t and \n with tab and newline accordingly) and [^ \n\t] to match a non-whitespace string. Save this answer.

How do you match everything except with regex?

How do you ignore something 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 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.

Does Matcher class matches the regular expression against the text provided?

It is used to create a matcher that will match the given input against this pattern. 5. It is used to compile the given regular expression and attempts to match the given input against it.


2 Answers

You need a negative lookahead assertion - something like this:

/^one two(?!.*three)/m

Here's a tutorial on lookahead/lookbehind assertions

Note: I've added the 'm' modifier so that ^ matches the start of a line rather than the start of the whole string.

like image 138
Paul Dixon Avatar answered Oct 09 '22 17:10

Paul Dixon


^one two(?!.*three)
like image 35
PEZ Avatar answered Oct 09 '22 15:10

PEZ