【问题标题】:I want to add a named variable in the output of the regular expression我想在正则表达式的输出中添加一个命名变量
【发布时间】:2021-02-23 18:15:00
【问题描述】:

我有一个格式为 abc.xyz 的名字,其中 abc 是名字,xyz 是姓氏。我想创建一个正则表达式,它将输出为first name = 'abc' and last name= 'xyz'

我有这个正则表达式:re.findall(r'(\w+)\b.\b(\w+)',a) where a=abc.xyz 并且输出是[("abc","xyz)"] 有什么我们可以在正则表达式本身中写的东西,它给出的输出是这样的first name = 'abc' and last name= 'xyz'

【问题讨论】:

  • 否;还有很多其他工具可以格式化正则表达式的结果。
  • 试试这个(?'你的正则表达式')
  • @Ade_1 你能输入吗,我打不开
  • 你想得到确切的字符串first name = 'abc' and last name= 'xyz'吗?

标签: python regex regex-group python-re


【解决方案1】:

尝试使用(?P<name> expr) 格式。例如:

(?P<first_name>\w+)\b.\b(?P<last_name>\w+)

Regex Demo(见右侧命名组名)

注意 Python 的正确语法是 (?P&lt;name&gt; expr)(带 P)而不是 (?&lt;name&gt; expr)(不带 P)

然后你可以使用groupdict()的方法得到一个包含所有命名组的字典,格式为name : text

示例代码:

m = re.match(r'(?P<first_name>\w+)\b.\b(?P<last_name>\w+)',a)
print(m.groupdict())

Output:
{'first_name': 'abc', 'last_name': 'xyz'}

那么你可以使用下面的代码来得到你想要的:

first_name = m.groupdict()['first_name']
last_name = m.groupdict()['last_name']

【讨论】:

  • 这看起来不错我也试过了,但我希望我能找到一些东西以便获得这种格式。虽然字典可以用作临时输出。
  • 请注意,当您使用 Python 时,您可能需要在 (?&lt; 之间的 P(即 (?P&lt;name&gt; 而不仅仅是 (?&lt;name&gt;。其他正则表达式风格,例如 PHP 不需要需要 P,但 Python 需要它。
【解决方案2】:

最好在搜索中使用分组

your_regex= re.search(?<a>\w+)\b.\b(?<b>\w+)
your_regex.group('a')
your_regex.group('b')

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 2013-11-05
    • 1970-01-01
    相关资源
    最近更新 更多