简体   繁体   English

相当于Perl的Python正则表达式

[英]Python regex equivalent for perl

what is the equivalent of following Perl condition in Python 相当于在Python中遵循Perl条件

if($line=~/DramBase/)

I tried the following but it didn't match(the line at the bottom) 我尝试了以下操作,但不匹配(底部的行)

if(re.match( r'DramBase', line)):

I had to change it to 我不得不将其更改为

if(re.match( r'.*DramBase', line)):

to match this line 匹配这条线

# -DF0.CCM0.DramBaseAddress1 0x00004001

Is there a flag to match it anywhere on the line without explicitly matching starting characters ? 是否有一个标志可以在行中的任何位置进行匹配,而无需显式地匹配起始字符?

You need to use re.search , not re.match . 您需要使用re.search而不是re.match re.match only matches as the beginning of the string, while re.search matches anywhere, like in Perl. re.match只匹配字符串的开头,而re.search匹配任何地方,例如Perl。

See re — Regular expression operations for an explanation 请参阅re-正则表达式操作以获取解释

re.match(pattern, string, flags=0) re.match(模式,字符串,标志= 0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. 如果字符串开头的零个或多个字符与正则表达式模式匹配,则返回相应的匹配对象。 Return None if the string does not match the pattern; 如果字符串与模式不匹配,则返回None;否则返回false。 note that this is different from a zero-length match. 请注意,这与零长度匹配不同。

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line. 请注意,即使在MULTILINE模式下,re.match()也只会字符串的开头而不是每行的开头进行匹配。

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()). 如果要在字符串中的任意位置找到匹配项,请改用search() (另请参见search()vs. match())。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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