For example, I am honored to announce that the author of this bad regular expression is me. The regular expression originating from Unix has always been the Swiss army knife for string processing. Today, I wrote a program with this knife, and the result is not consistent with the expectation. As follows/^ Task0 | Task1 | Task10 $/The expected result of this regular expression... SyntaxHighlighter. all ();
For example, I am honored to announce that the author of this bad regular expression is me.
The regular expression originating from Unix has always been the Swiss army knife for string processing. Today, I wrote a program with this knife, and the result is not consistent with the expectation. As follows:
/^ Task0 | Task1 | Task10 $/
This regular expression is expected to match only one of Task0, Task1, and Task10, but it can match any string starting with Task1, such as Task11 and Task12.
My colleague said that this regular expression matches strings like tasktask10, which is obviously incorrect and should not be confused. | (OR) indicates matching the expression on the left or right, not a character.
The following regular expression can produce the expected results.
/^ (Task0 | Task1 | Task10) $/
What are the differences between the two regular expressions?
What should I do?
The definition of | (OR) is as follows:
| (OR) indicates that the Left and Right expressions match any one. It always tries to match the expression on the left first. Once the expression is successful, the expression on the right is skipped. If | is not included in parentheses (), its range is the entire regular expression.
Now let's take a look at/^ Task0 | Task1 | Task10 $/. If the test string is Task11.
1. First test with ^ Task0 to check whether Task11 meets the requirement. If Task0 is used as the start, the test result is not satisfied.
2. Use Task1 to test Task11 and check whether Task11 contains Task 1. The test result is satisfied, the test is complete, and the test result is matched.
Check/^ (Task0 | Task1 | Task10) $/. It is assumed that the test string is Task11.
1. Test whether Task11 starts with Task0, Task1, and Task10. The test result must start with Task1.
2. It is followed by a $ symbol, and the string must end. That is to say, only one of Task0, Task1, and Task10 are matched, so the test results do not match.
I am not careful to write a mistake. Here I will make a simple description to remind everyone, but to remind myself.