捕获字符串中的子字符串 - 动态
Capture substring within a string - dynamically
我有一个字符串:
ostring = "Ref('r1_featuring', ObjectId('5f475')"
我想做的是搜索字符串并检查它是否以 Ref
开头,如果是,则应删除字符串中的所有内容并保留子字符串 5f475
.
我知道这可以使用像这样的简单替换来完成:
string = ostring.replace("Ref('r1_featuring', ObjectId('", '').replace("')", '')
但我不能这样做,因为它需要全部是 动态的,因为每次都会有不同的字符串。因此,我需要以一种搜索字符串并检查它是否以 Ref
开头的方式来执行此操作,如果以 Ref
开头,则获取字母数字值。
期望输出:
5f475
我们将不胜感激。
像那样?
>>> import re
>>> pattern = r"Ref.*'(.*)'\)$"
>>> m = re.match(pattern, "Ref('r1_featuring', ObjectId('5f475')")
>>> if m:
... print(m.group(1))
...
5f475
# >= python3.8
>>> if m := re.match(pattern, "Ref('r1_featuring', ObjectId('5f475')"):
... print(m.group(1))
...
5f475
无正则表达式的解决方案:)
ostring = "Ref('r1_featuring', ObjectId('5f475')"
if ostring.startswith("Ref"):
desired_part = ostring.rpartition("('")[-1].rpartition("')")[0]
我有一个字符串:
ostring = "Ref('r1_featuring', ObjectId('5f475')"
我想做的是搜索字符串并检查它是否以 Ref
开头,如果是,则应删除字符串中的所有内容并保留子字符串 5f475
.
我知道这可以使用像这样的简单替换来完成:
string = ostring.replace("Ref('r1_featuring', ObjectId('", '').replace("')", '')
但我不能这样做,因为它需要全部是 动态的,因为每次都会有不同的字符串。因此,我需要以一种搜索字符串并检查它是否以 Ref
开头的方式来执行此操作,如果以 Ref
开头,则获取字母数字值。
期望输出:
5f475
我们将不胜感激。
像那样?
>>> import re
>>> pattern = r"Ref.*'(.*)'\)$"
>>> m = re.match(pattern, "Ref('r1_featuring', ObjectId('5f475')")
>>> if m:
... print(m.group(1))
...
5f475
# >= python3.8
>>> if m := re.match(pattern, "Ref('r1_featuring', ObjectId('5f475')"):
... print(m.group(1))
...
5f475
无正则表达式的解决方案:)
ostring = "Ref('r1_featuring', ObjectId('5f475')"
if ostring.startswith("Ref"):
desired_part = ostring.rpartition("('")[-1].rpartition("')")[0]