【问题标题】:What is the correct way to use a regular expression to replace non-alpha characters at the beginning of a string in Python? [duplicate]在Python中使用正则表达式替换字符串开头的非字母字符的正确方法是什么? [复制]
【发布时间】:2017-10-25 17:22:43
【问题描述】:

注意:我看过其他帖子,例如“Re.sub not working for me”。这是 1) 用于特定模式,2) 用于匹配字符串中“任何地方”的特定模式。这与那个帖子不同 1) 因为它寻找的不是特定模式而是非字母数字正则表达式,以及 2) 因为它寻找的是替换字符串开头的“特定”。

谨请您取消将此标记为重复,因为它不是。

我有一个方法,它接收一个字符串并尝试使用正则表达式将字符串开头的所有非字母字符替换为固定字符串(“BEGINNING_”)...

def m_getWebSafeString(self, dirtyAttributeName):
  cleanAttributeName = ''.join(dirtyAttributeName)
  # Deal with beginning of string...
  re.sub('^[^a-zA-z]*','BEGINNING_',cleanAttributeName)
  if "BEGINNING_" in cleanAttributeName:
    print ' -- NEW STRING = {}'.format(cleanAttributeName)
return cleanAttributeName

它运行没有错误,但似乎没有正确替换字符串。比如触发打印语句的IF语句就不会发生。

我做错了什么?

【问题讨论】:

  • 清理后没有给cleanAttributeName赋值。
  • 您正在执行替换,然后将结果丢弃,因为您没有将其存储在任何地方。

标签: python regex


【解决方案1】:

你需要将re.sub()的结果赋值给某事:

def m_getWebSafeString(self, dirtyAttributeName):
  cleanAttributeName = ''.join(dirtyAttributeName)
  # Deal with beginning of string...

  cleanAttributeName = re.sub('^[^a-zA-z]*','BEGINNING_',cleanAttributeName) # ORIGINAL REFERENCE
  # --- ^ --- here

  if "BEGINNING_" in cleanAttributeName:
    print ' -- NEW STRING = {}'.format(cleanAttributeName)
return cleanAttributeName

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    相关资源
    最近更新 更多