删除字符串前的 n

时间:2021-01-22 19:01:10

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

我想删除此字符串中每个大写单词和数字开头的不需要的 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

1 个答案:

答案 0 :(得分:2)

你可以使用

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