【问题标题】:force re.search to include # and $强制 re.search 包括 # 和 $
【发布时间】:2022-11-25 05:54:10
【问题描述】:

我试图在 Python 中使用 re 获取两个标记之间的子字符串,例如:

import re
test_str = "#$ -N model_simulation 2022"

# these two lines work
# the output is: model_simulation
print(re.search("-N(.*)2022",test_str).group(1))
print(re.search(" -N(.*)2022",test_str).group(1))

# these two lines give the error: 'NoneType' object has no attribute 'group'
print(re.search("$ -N(.*)2022",test_str).group(1))
print(re.search("#$ -N(.*)2022",test_str).group(1))

我阅读了rehere的文档。它说“#”被故意忽略,以便输出看起来更整洁。

但就我而言,我确实需要包含“#”和“$”。我需要它们来识别我想要的字符串部分,因为“-N”在我的实际工作的整个文本字符串中不是唯一的。

有没有办法强制re包括那些?或者有没有不使用re的不同方式?

谢谢。

【问题讨论】:

  • 你试过原始字符串吗? match = r"#$ -N model_simulation 2022"
  • 试试这个 print(re.search("\$ -N(.*)2022",test_str).group(1)) print(re.search("\#\$ -N(.*)2022",test_str) .group(1))

标签: python python-3.x python-re


【解决方案1】:

您可以使用 转义两者,例如,

print(re.search("#$ -N(.*)2022",test_str).group(1))
# output  model_simulation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多