贪婪模式和非贪婪模式
贪婪匹配:在满足匹配时,匹配尽可能长的字符串,默认情况下,采用贪婪匹配
string pattern1 = @"a.*c"; // greedy match
Regex regex = new Regex(pattern1);
regex.Match("abcabc"); // return "abcabc"
非贪婪匹配:在满足匹配时,匹配尽可能短的字符串,使用?来表示非贪婪匹配
string pattern1 = @"a.*?c"; // non-greedy match
Regex regex = new Regex(pattern1);
regex.Match("abcabc"); // return "abc"
几个常用的非Pattern
*? 重复任意次,但尽可贪婪匹配能少重复
+? 重复1次或更多次,但尽可能少重复
?? 重复0次或1次,但尽可能少重复
{n,m}? 重复n到m次,但尽可能少重复
{n,}? 重复n次以上,但尽可能少重复
、、、、、、、、、、、、、、、、、、、、、、、
line
=
'my title="sw engineer". His is "hello world"'
m
=
re.search(r
'title="(.*?)"'
, line)
m.group(
1
)
>> sw engineer
# 如果没有 ?, 则会抓到最长的两个双引号之间的内容
m
=
re.search(r
'title="(.*)"'
, line)
m.group(
1
)
这个例子对于学习贪婪模式可能更合适。>> sw engineer
". His is "
hello world
for循环
>>> li = ['a', 'b', 'e'] >>> for s in li: (1) ... print s (2) a e >>> print "\n".join(li) (3) a e
(1) for 循环的语法同 list 解析相似。li 是一个 list,而 s 将从第一个元素开始依次接收每个元素的值。 (2) 像 if 语句或其它任意缩进块,for 循环可以包含任意数目的代码行。