由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 问个PYTHON烂问题
相关主题
Pattern matchingPython和perl都属于那种很难精通的语言
python gc questionpython的re怎么有很多莫名奇妙的行为, 我估计是bug吧
Re: 问个google面试题 (转载)Scala这次又被比下去了
Python:How to replace 2 different patterns in 1 line in filepattern search question in Python
怎样运行一个 Python script?没觉得Java比Python和Perl有啥优点
how to grep one of the strings?在c++下调用python
一个c++小问题求推荐Machine Learning经典教材
问一个Python thread的问题Python: 有一个混合了子list和string的list, 如何判断元素是list还是string?
相关话题的讨论汇总
话题: aaax话题: nxxyyy话题: string话题: match话题: raw
进入Programming版参与讨论
1 (共1页)
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'

1 (共1页)
进入Programming版参与讨论
相关主题
Python: 有一个混合了子list和string的list, 如何判断元素是list还是string?怎样运行一个 Python script?
问一个python的string split问题how to grep one of the strings?
Can I force/convert a string obj to a file obj in python ?一个c++小问题
没人觉得python的string是immutable不爽吗?问一个Python thread的问题
Pattern matchingPython和perl都属于那种很难精通的语言
python gc questionpython的re怎么有很多莫名奇妙的行为, 我估计是bug吧
Re: 问个google面试题 (转载)Scala这次又被比下去了
Python:How to replace 2 different patterns in 1 line in filepattern search question in Python
相关话题的讨论汇总
话题: aaax话题: nxxyyy话题: string话题: match话题: raw