【问题标题】:remove non alphabet chars from the beginning and the end of the string从字符串的开头和结尾删除非字母字符
【发布时间】:2019-07-07 09:30:10
【问题描述】:

我对正则表达式很陌生。我想从位于字符串开头和结尾的非字母字符中清除字符串。例如,如果我有以下字符串: .,How are you? I am good, thanks!.,

我想得到: How are you? I am good, thanks

【问题讨论】:

  • re.sub 带有空字符串的模式^[^a-zA-Z]|[^a-zA-Z]$
  • 我的错,我不想替换所有非字母字符。例如,如果我有这个字符串 .,How are you? I am good, thanks .! 我想得到 How are you? I am good, thanks
  • 我的正则表达式会这样做。尝试运行它。
  • 我试过这个import re regex = re.compile('^[^a-zA-Z]|[^a-zA-Z]$ ') regex.sub('', dirty)但它不起作用:/dirty = '.,How are you? I am good, thanks .!'
  • @Alan 如果您想实现 cmets 中的内容,您也需要更改您的问题。

标签: python regex string


【解决方案1】:

您可以使用正则表达式:

^[^a-zA-Z]+|[^a-zA-Z]+$

[^a-zA-Z] 表示“不是 a-z 或 A-Z”。 ^$ 分别表示字符串的开头和结尾。

用法:

>>> re.sub(r"^[^a-zA-Z]+|[^a-zA-Z]+$", "", ",. Hello, How are you?")
'Hello, How are you'

【讨论】:

    【解决方案2】:

    使用

    (\w|\s)+
    

    这意味着任何character(\w)space(\s) 至少有一个one-time repeat(+)

    Demo

    【讨论】:

      【解决方案3】:

      您可以使用strip 函数从字符串的开头和结尾删除字符

      import string
      nonalphabet= "".join([c for c in string.printable if c not in string.ascii_letters])
      s = ".,how are you ?"
      print (s.strip(nonalphabet))
      

      将输出how are you

      【讨论】:

        猜你喜欢
        • 2014-05-04
        • 1970-01-01
        • 1970-01-01
        • 2017-07-07
        • 2013-01-12
        • 1970-01-01
        • 2011-12-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多