Code
# ! /Usr/bin/ENV Python
# Coding = UTF-8
Import Re
Str = R ' <Docitem key = "founded_place"> <! [CDATA [Guangdong, Shenzhen, China]> </docitem> '
R = Re. Compile (R ' <Docitem key = "(. *)"> (. *) </docitem> ' )
M = R. Match (STR)
PrintM. group (0)
PrintM. Group (1)
PrintM. Group (2)
Print '========================================================== ==='
Str2=M. Group (2)
Str2=Str
PrintStr2
R2=Re. Compile (R". * <! \ [CDATA \ [(. *?)]>")
M2=R2.match (str2)
PrintM2.group (1)
<Docitem key = "founded_place"> <! [CDATA [Guangdong, Shenzhen, China]> </docitem>
Founded_place <! [CDATA [Guangdong, Shenzhen, China] >==================================== =============< docitem key = "founded_place"> <! [CDATA [China Guangdong Shenzhen]> </docitem> China Guangdong Shenzhen
This is different from the Perl regular expression. In Perl, the mode string is(R"<! [CDATA [(. *?)]>"), But in Python, ". *" must be added before it can be used normally, and "[" must be added with backslash escape. The formula is as follows:
(R". * <! \ [CDATA \ [(. *?)]>")
II
Another problem is that python does not handle the encoding problem very well. In many cases, the encoding mode needs to be changed for different characters.
#! /Usr/bin/ENV Python
# Coding = UTF-8
Import sys
Reload (sys)
SYS. setdefaultencoding ('gbk ')
Import re
Pchinese = Re. Compile (UR '([\ u4e00-\ u9fa5] +) +? ', Re. U)
S = u'2017 test with string 67890,45 this is another 44 Ha'
M = pchinese. findall (s)
If M:
Print ('|'. Join (m ))
Else:
Print ('no found! ')
3.
#! /Usr/bin/ENV Python
# Coding = UTF-8
#! /Usr/bin/ENV Python
# Coding = UTF-8
Import re
Import sys
Reload (sys)
SYS. setdefaultencoding ('gbk ')
Str1 = R' <docitem key = "founded_place"> <! [CDATA [Guangdong, Shenzhen, China]> </docitem>'
# Str1 = r "CDATA [Guangdong and Shenzhen, China]"
# Str1 = Unicode (str1, 'utf8 ')
Print type (str1)
Re2 = r ". * CDATA \[(.*?) \]"
# Re2 = Unicode (re2, 'utf8 ')
# Print type (re2)
R = Re. Compile (re2) # [\ u4e00-\ u9fa5]
M = R. Match (str1)
Print M. group (0)
Print M. Group (1)