In Python, regular expressions also have features that are more distinctive than other programming languages. That is to support loose regular expressions.
In some cases, the regular expression will be written very long, at this time, maintenance is a problem. and the loose regular expression is the solution to this problem.
Use the last grouped code as an example:
1 ImportRe2Userinput = input ("Please input test string:")3m = Re.match (r'(\d{3,4})-(\d{8})', Userinput)4 ifm:5 Print('Area code:'+ M.group (1))6 Print('Number:'+ M.group (2))7 Else:8 Print('Format Error')
Now let's say we've been writing this code for a long time and don't know the meaning of \d{3,4} and \d{8}.
It's good to write a note at the beginning, but we can't write it.
1 # \d{3,4} represents the area code, \D{8} represents the number
Such a comment. Don ' t repeat youself. The loose regular expression is used.
1 ImportRe2Userinput = input ("Please input test string:")3Regex = R" "4 (5 \d{3,4} # area code6 )7 -# The delimiter between the area code and the number8 (9 \d{8} # numberTen ) One " " Am =Re.match (regex,userinput,re. VERBOSE) - ifm: - Print('Area code:'+ M.group (1)) the Print('Number:'+ M.group (2)) - Else: - Print('Format Error')
"represents multiple lines of text (and can also be used as a representation of document annotations).
It is worth noting that there are now a lot more whitespace in the string and comments (although they are now compiled as part of the string), but the effect is consistent.
It is also important to note that at the end of the Re.match method, the Re.verbose parameter is used, which indicates that the current regular expression is a loose regular expression. In Re.split and other methods, you need to use this parameter if you need to use a loose regular expression.
Python learning Regular Expressions in -38.python (ii)