Test data:
For example, in the above simple log entries, we want to achieve two goals:
1. Filter out the data on No. 8;
2. Find the entries that do not contain the robots.txt string (as long as the URL contains robots.txt, all will be filtered out).
The look-ahead syntax is:
(?!匹配模式)
Let’s first achieve the first goal - matching entries that do not start with a specific string.
Here we want to exclude a continuous string, so the matching pattern is very simple, which is 2009-07-08. The implementation is as follows:
^(?!2009-07-08).*?$
Using Expresso, we can see that the results indeed filter out the data on No. 8.
Next, let’s achieve the second goal—exclude entries containing specific strings.
According to the way we wrote it above, I took a look at it:
^.*?(?!robots\.txt).*?$
The description of this regular rule in vernacular is: any character at the beginning, and then do not follow the continuous string of robots.txt. Then followed by any number of characters, the end of the string.
Run the test and found that:
did not achieve the effect we wanted. Why is this? Let’s add two capture groups to the above regular expression to debug it:
^(.*?)(?!robots\.txt)(.*?)$
Test results:
We see that, first The first group matched nothing, but the second group matched the entire string. Let’s go back and analyze the regular expression just now.
In fact, when the regular engine parses area A, it has already started to perform the look-ahead work of area B. At this time, it was found that the match was successful when area A was Null - .* originally allowed to match null characters, and the look-ahead condition was met. The string "2009" followed immediately after area A, not robots. Therefore, the entire matching process successfully matches all entries.
After analyzing the reason, we corrected the above regular expression and moved .*? into the look-ahead expression, as follows:
^(?!.*?robots).*$
Test result:
Recommended tutorial: Getting started with java development
The above is the detailed content of Java uses regular expressions to match strings that do not contain a certain rule. For more information, please follow other related articles on the PHP Chinese website!