Arjun Arjun - 2 days ago 5
Java Question

Regex Patter to negate a character

I'm having a statement as below

#sv_q = " INSERT INTO alertuser.REALTIME


I'm trying to create a regex to match this line from a set of lines from the file, whenever insert keyword is used. But since a '#' is used at the beginning I wouldn't want to consider this line. How to achieve this. I tried the below regex, but still this line is getting considered, can anyone suggest how to achieve this?

static Pattern tracePattern = Pattern.compile("(?!\\#).*insert\\s*into",Pattern.CASE_INSENSITIVE);
Matcher localMatcher = tracePattern.matcher(line);
if (localMatcher.find()) {
// doing some checks
}

Answer

If you want to use .find(), you need to anchor the pattern at the beginning with ^ or \A. Besides, you'd better use word boundaries to only match whole words insert and into, and use \s+ instead of \s* to enforce at least 1 occurrence of a whitespace between insert and into:

"^(?!#).*\\binsert\\s+into\\b"

You could shorten your solution to

if (s.matches("(?i)(?!#).*\\binsert\\s+into\\b.*")) { doing some checks} 

The matches() method requires a full string match, and thus, you need to add the .* at the end. Also, the Pattern.CASE_INSENSITIVE option can be used inline with the help of the embedded flag option (?i). If your input can contain line breaks, use (?si) instead of (?i).

Comments