【问题标题】:remove n before a string删除字符串前的 n
【发布时间】:2021-01-22 19:01:10
【问题描述】:

我想删除此字符串中每个大写单词和数字开头的不需要的 r 和 n。我试过正则表达式。不确定正则表达式或其他方法在这里是否有用。

这是我尝试使用的代码:

text = "nFamily n49 new nTom"

regex_pattern =  re.compile(r'.*n[A-Z][a-z]*|[0-9]*\s')
matches = regex_pattern.findall(text)
for match in matches:
    text = text.replace(match," ")
print(text)

预期输出:

Family 49 new Tom

【问题讨论】:

  • 使用re.sub(r'\b[rn](?=[A-Z\d])', "", text)

标签: python python-3.x regex data-extraction


【解决方案1】:

你可以使用

text = re.sub(r'\bn(?=[A-Z0-9])', '', text)

请参阅regex demo

详情

  • \b - 这里是一个词的开始
  • n - n
  • (?=[A-Z0-9]) - 正向前瞻,要求在当前位置的右侧紧邻出现一个大写的 ASCII 字母或数字。

Python demo

import re
rx = r"\bn(?=[A-Z0-9])"
text = "nFamily n49 new nTom"
print( re.sub(rx, '', text) )
# => Family 49 new Tom

【讨论】:

    猜你喜欢
    • 2020-04-05
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    相关资源
    最近更新 更多