开发者

C Preprocessing with Python Regular Expressions

I've never used regular expressions before and I'm struggling to make sense of them. I have strings in the form of 'define(__a开发者_StackOverflow中文版rch64__)' and I just want the __arch64__.

import re  
mystring = 'define(this_symbol)||define(that_symbol)'  
pattern = 'define\(([a-zA-Z_]\w*)\)'  
re.search(mystring, pattern).groups()  

(None, None)

What doesn't search return 'this_symbol' and 'that_symbol'?


You have the parameters of search() in the wrong order, it should be:

re.search(pattern, mystring)

Also, backslashes are escape characters in python strings (for example "\n" will be a string containing a newline). If you want literal backslaches, like in the regular expression, you have to escape them with another backslash. Alternatively you can use raw strings that are marked by an r in front of them and don't treat backslashes as escape characters:

pattern = r'define\(([a-zA-Z_]\w*)\)'


You must differentiate between the symbol ( and the regexp group characters. Also, the pattern goes first in re.search:

pattern = 'define\\(([a-zA-Z_]\w*)\\)'
re.search(pattern, mystring).groups()  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜