【问题标题】:how to remove non-alphanumeric characters except \ / @ + -:, | #如何删除除 \ / @ + -:, | 之外的非字母数字字符#
【发布时间】:2015-01-16 17:47:49
【问题描述】:

我有

import re

cadena = re.sub('[^0-9a-zA-Z]+', '', cadena)

如何删除除此之外的非字母数字字符 \ / @ + -:, | #

【问题讨论】:

  • 你的问题能更简洁吗?
  • cadena = re.sub('[^0-9a-zA-Z\/@+\-:,|#]+', '', cadena)
  • 由于某种原因没有工作问我为什么,现在是的

标签: python python-2.7 alphanumeric


【解决方案1】:

确保在字符类中转义反斜杠。使用原始字符串进行正则表达式,它消除了进一步转义的需要。

cadena = re.sub(r'[^0-9a-zA-Z\\/@+\-:,|#]+', '', cadena)

请注意,下划线被视为字母数字字符。如果不需要剥离,可以简化表达式。

cadena = re.sub(r'[^\w\\/@+\-:,|#]+', '', cadena)

【讨论】:

    【解决方案2】:

    示例 1: (我认为最简单的方法)

    # String
    string = 'ABC#790@'
    # Remove the #, @ and 7 from the string. (You can choose whatever you want to take out.)
    line = re.sub('[#@7]', '', string)
    # Print output
    print(line)
    

    示例 2:

    您还可以使用子字符串,这样您就可以查看每个位置,如果一个字母与您不想要的字符串中的字母匹配。 如果该字母是您想要保留的字母,则将该字母添加到一个新字符串中。否则你通过。

    例如: 字符串 's' 是您的字符串,字符串 'd' 包含您要过滤掉的字母。

    s = 'abc/geG#gDvs@h81'
    d = '#@/'
    e = ''
    i = 0
    j = 0
    l = len(s)
    g = len(d)
    a = False
    
    while i < l:
        # Grab a single letter
        letter1 = s[i:i+1]
        # Add +1
        i = i + 1
        # Look if the letter is in string d
        while j < g:
            # Grab a single letter
            letter2 = d[j:j+1]
            # Add +1
            j = j + 1
            # Look if letter is not the same.
            if (letter1 != letter2):
                a = True
            else: 
                a = False
                break
        # Reset j
        j = 0
        # Look if a is True of False. 
        # True: Letter does not contain letters from string d. 
        # False: Letter does contain letters from string d.
        if (a == True):
            e = e + letter1
        else: 
            pass
    
    # Print the result
    print(e)
    

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      相关资源
      最近更新 更多