วันอังคารที่ 19 พฤษภาคม พ.ศ. 2552

Regular Expression Syntax (2)

มาต่อกับสัญลักษณ์ที่เหลือของ regular expression ในภาษาไพธอน

"." หมายถึง แทนตัวอักษรอะไรก็ได้


>>> import re
>>> my_pattern = '.at'
>>> raw_string = 'I love rat and cat'
>>> re.sub(my_pattern,'dog',raw_string)
'I love dog and dog'


"^" หมายถึง คำที่อยู่ด้านหน้า โดยวางไว้ข้างหน้าคำที่ต้องการค้นหา เหมือน \A


>>> my_pattern = '^dog'
>>> raw_string = 'dog dog dog'
>>> re.sub(my_pattern,'cat',raw_string)
'cat dog dog'


"$" หมายถึง คำที่อยู่ด้านหลัง โดยวางไว้ข้างหลังคำที่ต้องการค้นหา เหมือน \Z


>>> my_pattern = 'dog$'
>>> raw_string = 'dog dog dog'
>>> re.sub(my_pattern,'cat',raw_string)
'dog dog cat'


"*" เอาไว้ท้ายอักษรที่ต้องการสื่อว่าไม่มี หรือ มี และก็ซ้ำได้ด้วย


>>> my_pattern = 'ab*'
>>> raw_string = 'aa , abb , abbb , ba , bb , bc'
>>> re.sub(my_pattern,'-',raw_string)
'-- , - , - , b- , bb , bc'


"+" เอาไว้ท้ายอักษรที่ต้องการสื่อต้องมี และก็ซ้ำได้ด้วย


>>> my_pattern = 'ab+'
>>> raw_string = 'aa , abb , abbb , ba , bb , bc'
>>> re.sub(my_pattern,'-',raw_string)
'aa , - , - , ba , bb , bc'


"?" เอาไว้ท้ายอักษรที่ต้องการสื่อว่าไม่มี หรือ มี แต่ซ้ำไม่ได้


>>> my_pattern = 'ab?'
>>> raw_string = 'aa , abb , abbb , ba , bb , bc'
>>> re.sub(my_pattern,'-',raw_string)
'-- , -b , -bb , b- , bb , bc'

ไม่มีความคิดเห็น:

แสดงความคิดเห็น