需求:
打印字符串Do you like 12 or 34?中的12, 34
方法:
1. Python
a. Global function
import re
subject = "Do you like 12 or 34?"
result = re.findall(r"\d+",subject)
for i in result:
print i,
b. Compiled object
import re
reobj = re.compile(r"\d+")
result = reobj.findall(subject)for i in result:
print i,
引申: (返回match object)
for iter in re.finditer("\d+",subject):
print iter,
2. Tcl
set subject "Do you like 12 or 34?"
set result ""
set pos 0
while {[regexp -indices -start $pos -linestop {\d+} $subject offsets]==1} {
set pos [expr {1+[lindex $offsets 1]}]
lappend result [string range $subject [lindex $offsets 0] [lindex $offsets 1]]
}
foreach i $result {
puts "$i"
}
原文链接:https://www.f2er.com/regex/361737.html