简体   繁体   中英

Can't understand this line of Python code

text1 = '11/27/2012'
import re
if re.match(r'\d+/\d+/\d+', text1): 
  print('YES')

I'm a beginner in Python. I know a thing or two about Regular expressions in Python.. for instance : \\d refers to matching 0 or more digits.

What is the above expression - line 3 - doing? More specifically, what is the significance of writing '\\d+/\\d+/\\d+' ?

text1 = '11/27/2012' 

Sets text1 with the string value.

import re 

Imports the regex module.

if re.match(r'\d+/\d+/\d+', text1)

True if text1 matches the regex '\\d+/\\d+/\\d+', otherwise False . The regex '\\d+/\\d+/\\d+' describes a number containing one or more digits followed by a "/", followed by another number of one or more digits, followed by a "/", followed by yet another number of one or more digits. A date in otherwords, although it will also match "123/12345/1234567" which is not a date so there are better regex expressions for matching dates than this particular one.

print('YES')

If the previous statement is True print "Yes" in the console window, otherwise nothing is printed.

So this code will output YES since text1 contains a correctly formatted date in accordance with the regex. If you play around with the value stored in text1 you can test the behaviour of the regex, ie test if your code outputs YES or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM