相关疑难解决方法(0)

Python正则表达式 - r前缀

任何人都可以解释为什么下面的示例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)

python regex string literals prefix

69
推荐指数
3
解决办法
7万
查看次数

使用正则表达式过滤列表

我认为这是一项简单的任务,但我是 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)

每个项目将包含两个“-”,但我只想获取“-”两侧带有文本的项目。

python regex python-2.7

7
推荐指数
2
解决办法
3万
查看次数

Python的 - 我应该找一个句号(.句号或)使用正则表达式时将使用字符串前缀R'

我想知道使用字符串前缀"R"的时候还是不找使用python正则表达式句号(句号)时,我得到了相同的结果的原因.

阅读数源(下面的链接)的倍数次,用代码尝试找到相同的结果(同样见下文)后,我仍然不确定的:

  1. 是什么时候使用前缀字符串"r"和不使用字符串前缀"R",寻找使用正则表达式一个时期的区别?
  2. 哪种方式被认为是使用带有字符串前缀"r"或没有字符串前缀"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

正则表达式用其原始文件替换"转义"字符

Python正则表达式 - r前缀

r前缀用于原始字符串 http://forums.udacity.com/questions/7000217/r-prefix-is-for-raw-strings

python regex string

2
推荐指数
1
解决办法
358
查看次数

如何从带有日期的字符串列表中过滤掉字符串?

如何过滤掉这个列表,以便我们只留下 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)

python

2
推荐指数
1
解决办法
422
查看次数

标签 统计

python ×4

regex ×3

string ×2

literals ×1

prefix ×1

python-2.7 ×1