简体   繁体   中英

Matching a string that does not contain a fragment - using regexp

I have a file (basically a log file) - with the following lines in it:

Error; 1 no match CIRCLE more.
Info; 2 should not match
Error; 3 should : match SHAPE 'abc'.
Debug; 4 should not match
Error; 5 CIRCLE / again
Error; 6 TRIANGLE should match

I want to find/match all of the complete lines that start with 'Error;' but do not have a word 'CIRCLE' in that line. So I want to find lines 3 and 6:

Error; 3 should : match SHAPE 'abc'.
Error; 6 TRIANGLE should match

The pattern I start with (Error;).+ gives me all the 'Error' lines, but I am not sure how to exclude the CIRCLE ones. Should be something very basic using [^ ... ] or a look-ahead I think.

Here I was playing with it online: http://regexr.com/39kig

^Error(?!.*?circle).*$

Try this.Do not forget to set i , m , g flags.See demo.

http://regex101.com/r/hQ1rP0/17

Use the below regex which uses negative lookahead . Don't forget to add multiline modifier if your regex contain anchors ( ^ - which denotes the start of a line, $ - means the end of a line ).

^Error;(?!.*?CIRCLE).*$

DEMO

> var r = "Error; 1 no match CIRCLE more.\nInfo; 2 should not match\nError; 3 should : match SHAPE 'abc'.\nDebug; 4 should not match\nError; 5 CIRCLE / again\nError; 6 TRIANGLE should match";
undefined
> var m = r.match(/^Error;(?!.*?CIRCLE).*$/gm)
undefined
> console.log(m)
[ 'Error; 3 should : match SHAPE \'abc\'.',
  'Error; 6 TRIANGLE should match' ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM