Regex negative look ahead not giving desired result

(Manish Meena) #1

I am having two strings as written below:

String s1= "6015603 06/12/2017 06/12/2017 02:45:28 PM - BIL/001347764403/LOAN/NSP CR  20,000.00  8,381.002 S 6156702 06/12/2017 06/12/2017";

String s2="6015603 06/12/2017 06/12/2017 - BIL/001347764403/LOAN/NSP CR  20,000.00  8,381.002 S 6156702 06/12/2017 06/12/2017";

and a regular expression like below:

String regex="[0-9]+\s+[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}\s+[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}\s*(?![0-9]{2}[:][0-9]{2}[:][0-9]{2}\s*(AM|PM)).*?(?=([0-9]+\s*[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}+\s+[0-9]{2}[\/][0-9]{2}[\/][0-9]{4})|\\Z)";

As you can see I have used negative look ahead to avoid time

(?![0-9]{2}[:][0-9]{2}[:][0-9]{2}\s*(AM|PM))

but when I am running the pattern matching both strings are matching. I want string s1 to ignore. What is wrong here that I am doing?

(Karen Barker) #2

Hi @Manish_Meena,

You’re just missing a \s* from the start of the negative look ahead. The regex should look like:

[0-9]+\s+[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}\s+[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}\s*(?!\s*[0-9]{2}[:][0-9]{2}[:][0-9]{2}\s*(AM|PM)).*?(?=([0-9]+\s*[0-9]{2}[\/][0-9]{2}[\/][0-9]{4}+\s+[0-9]{2}[\/][0-9]{2}[\/][0-9]{4})|\\Z)

:thumbsup: