任何人都可以解释为什么下面的示例1有效,何时r不使用前缀?我认为r只要使用转义序列,就必须使用前缀.示例2和示例3证明了这一点.
# example 1
import re
print (re.sub('\s+', ' ', 'hello there there'))
# prints 'hello there there' - not expected as r prefix is not used
# example 2
import re
print (re.sub(r'(\b\w+)(\s+\1\b)+', r'\1', 'hello there there'))
# prints 'hello there' - as expected as r prefix is used
# example 3
import re
print (re.sub('(\b\w+)(\s+\1\b)+', '\1', 'hello there there'))
# prints 'hello there there' - as expected as r prefix is not used
Run Code Online (Sandbox Code Playgroud) 我认为这是一项简单的任务,但我是 regex 的新手,所以无法弄清楚。我想过滤一个包含以下内容的列表:“ANY”-“ANY”-“ANY”
输入:
List1 = ["AB.22-01-01", "AB.33-01-44", "--4", "AA.44--05", "--"]
Run Code Online (Sandbox Code Playgroud)
输出:
List2 = ["AB.22-01-01", "AB.33-01-44"]
Run Code Online (Sandbox Code Playgroud)
每个项目将包含两个“-”,但我只想获取“-”两侧带有文本的项目。
我想知道使用字符串前缀"R"的时候还是不找使用python正则表达式句号(句号)时,我得到了相同的结果的原因.
阅读数源(下面的链接)的倍数次,用代码尝试找到相同的结果(同样见下文)后,我仍然不确定的:
re.compile("\.").sub("!", "blah.")
Run Code Online (Sandbox Code Playgroud)
"胡说!"
re.compile(r"\.").sub("!", "blah.")
Run Code Online (Sandbox Code Playgroud)
"胡说!"
re.compile(r"\.").search("blah.").group()
Run Code Online (Sandbox Code Playgroud)
''
re.compile("\.").search("blah.").group()
Run Code Online (Sandbox Code Playgroud)
''
我看过的资料来源:
Python文档:字符串文字 http://docs.python.org/2/reference/lexical_analysis.html#string-literals
r前缀用于原始字符串 http://forums.udacity.com/questions/7000217/r-prefix-is-for-raw-strings
如何过滤掉这个列表,以便我们只留下 yyyy-mm-dd 格式的字符串列表?
2021-11-11
2021-10-01
some_folder
some_other_folder
Run Code Online (Sandbox Code Playgroud)
这样我们最终得到一个像这样的列表:
2021-11-11
2021-10-01
Run Code Online (Sandbox Code Playgroud)
如果列表有前缀怎么办?
root/2021-11-11
root/2021-10-01
user/some_folder
root/some_other_folder
Run Code Online (Sandbox Code Playgroud)
我们希望最终得到:
root/2021-11-11
root/2021-10-01
Run Code Online (Sandbox Code Playgroud)