【问题标题】:General Expression Re.sub()一般表达式 Re.sub()
【发布时间】:2020-06-12 03:12:08
【问题描述】:

我写了这段代码:

result= re.sub(r"\s\d{3}",r"\0","My phone number is 999-582-9090")
print(result)

得到输出:

My phone number is( )-582-9030

为什么我的号码没有打印出来? 感谢您的帮助

【问题讨论】:

  • 您的预期结果是什么?
  • @user202729 -- 我想这很明显; My phone number is(999)-582-9030
  • @user202729 它是My phone number is(999)-582-9030

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


【解决方案1】:

你可以试试:

\s+(\d{3})(?=-)

上述正则表达式的解释:

\s+ - 表示一个或多个空格字符。

(\d{3}) - 表示捕获前 3 位数字的捕获组。

(?=-) - 表示仅在 - 之前断言三位数字的正向前瞻。

你可以在here.找到演示

在python中的实现:

import re

regex = r"\s+(\d{3})(?=-)"

test_str = "My phone number is 999-582-9090"

subst = " (\\1)"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0)

if result:
    print (result)

您可以在here.找到上述代码的示例运行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-29
    • 2012-08-18
    相关资源
    最近更新 更多