Groovy tip 35 Regular Expression 4
We know that in regular expressions, some strings are used to express some special purposes. For example, "." represents all characters; "^" represents non-; and so on. When we see these usage, we can ask in turn, if "." represents all the characters, then what will be used to match "." In the string?
To solve this problem, you must add "/" to the regular expression to match the original string. The following is an example:
Println'A. C' = ~ /A/. c/
The running result is:
True
Other such characters include :"{","[","(",") ","/"," ^ "," $ "," | ","? "," * "And" +.
With such a principle, we can understand some strange problems in the encoding process. For example, we often operate on the file name string, as shown in the following file name:
DefFn = 'test.txt'
We want to split the file name and type. We often want to use the split method as follows:
DefFNS = fn. Split ('.')
PrintlnFNS
This idea is very direct and simple, but the result is:
{}
This is obviously not the result we want.
Where is the problem? Because "." matches all characters and can match any character in "test.txt", the split method cannot be used.
The correct code is as follows:
DefFns1 = fn. Split (//./)
PrintlnFns1
The running result is:
{"Test", "TXT "}
This is what we want.
It is worth noting that "." does not really match all characters, and some characters cannot match either. The following code can match:
Println'Abc/ndef '= ~ /A. C/ndef/
The running result is:
True
But the following code cannot match:
Println'Abc/ndef '= ~ /ABC.Def/
The running result is:
False
That is, "." does not match "/N" -- line break.
If we have to "." To match all the characters, there is also a way ,"(? S) "to force it to match all characters. The sample code is as follows:
Println'Abc/ndef '= ~ /(? S) ABC.Def/
The running result is:
True
For "(? S) "such stuff, we call it a flag, "(? S) ", there are several more useful signs.
The first is "(? I) ", used as a case-insensitive flag, the following sample code:
Println'Abcdef' = ~ /ABC (? I)Def/
The running result is:
True
The following code is used:
Println'Abcdef' = ~ /Abcdef/
The running result is:
False
Since "(? I) ", used as a flag to ignore the case, you need to end with a flag to ignore the case. This is "(? -I) ", the following code is matched:
Println'Abcdefg' = ~ /ABC (? I)Def(? -I) g/
The running result is:
True
The following code does not match:
Println'Abcdefg' = ~ /ABC (? I)Def(? -I) g/
The running result is:
False