y***a 发帖数: 840 | 1 为啥第一个没做替换? 如果是RAW STRING, 应该是MATCH的啊, 反而第二个没用’r
', 不是RAW STRING啊
1. >>> re.sub(r'x\nxx', 'zzz', r'aaax\nxxyyy')
'aaax\nxxyyy'
2. >>> re.sub(r'x\nxx', 'zzz', 'aaax\nxxyyy')
'aaazzzyyy' | c*********e 发帖数: 16335 | 2 什么是raw string,你说说。
’r
【在 y***a 的大作中提到】 : 为啥第一个没做替换? 如果是RAW STRING, 应该是MATCH的啊, 反而第二个没用’r : ', 不是RAW STRING啊 : 1. >>> re.sub(r'x\nxx', 'zzz', r'aaax\nxxyyy') : 'aaax\nxxyyy' : 2. >>> re.sub(r'x\nxx', 'zzz', 'aaax\nxxyyy') : 'aaazzzyyy'
| i********g 发帖数: 72 | 3 In your code, r'x\nxx' is pattern, and r'aaax\nxxyyy' is the string to match.
You need to remove 'r' to get right. r'aaax\nxxyyy' is raw string
interpreted as [ aaax\nxxyyy ], However, 'aaax\nxxyyy' is NOT raw string, '\
n' is interpreted as new line;
If the pattern isn’t found, meaning xNEWLINExx is not equal to [x\nxx],
string is returned unchanged. That's why you get your first results.
Make sure the pattern get match.
Hope this helps!
’r
【在 y***a 的大作中提到】 : 为啥第一个没做替换? 如果是RAW STRING, 应该是MATCH的啊, 反而第二个没用’r : ', 不是RAW STRING啊 : 1. >>> re.sub(r'x\nxx', 'zzz', r'aaax\nxxyyy') : 'aaax\nxxyyy' : 2. >>> re.sub(r'x\nxx', 'zzz', 'aaax\nxxyyy') : 'aaazzzyyy'
| D*********e 发帖数: 646 | 4 http://stackoverflow.com/questions/30164054/raw-string-and-regular-expression-in-python
re.sub?
re.sub(pattern, repl, string)
pattern是个string literal,pattern里的r'\n'就是literally存储为'\n'。而string
里的r'\n'存储为'\\n',所以第一个不会match。
你可以试试:
re.sub('\n', 'Match!', '\n')
re.sub('\\n', 'Match!', '\n')
re.sub('\\\n', 'Match!', '\n')
re.sub('\\\\n', 'Match!', '\n')
’r
【在 y***a 的大作中提到】 : 为啥第一个没做替换? 如果是RAW STRING, 应该是MATCH的啊, 反而第二个没用’r : ', 不是RAW STRING啊 : 1. >>> re.sub(r'x\nxx', 'zzz', r'aaax\nxxyyy') : 'aaax\nxxyyy' : 2. >>> re.sub(r'x\nxx', 'zzz', 'aaax\nxxyyy') : 'aaazzzyyy'
|
|