删除字符串前的 n

remove n before a string

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

你可以使用

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