我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。


当前回答

对于其他语言,如德语,西班牙语,丹麦语,法语等包含特殊字符(如德语“Umlaute”ü, ä, ö),只需将这些添加到正则表达式搜索字符串:

例如德语:

re.sub('[^A-ZÜÖÄa-z0-9]+', '', mystring)

其他回答

#!/usr/bin/python
import re

strs = "how much for the maple syrup? $20.99? That's ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!]',r'',strs)
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)
print nestr

你可以添加更多的特殊字符,这将被“意味着什么,即他们将被删除”所取代。

s = re.sub(r"[-()\"#/@;:<>{}`+=~|.!?,]", "", s)

Python 2 . *

我认为只要filter(str。Isalnum,字符串)工作

In [20]: filter(str.isalnum, 'string with special chars like !,#$% etcs.')
Out[20]: 'stringwithspecialcharslikeetcs'

Python 3。*

在Python3中,filter()函数将返回一个可迭代对象(而不是与上面不同的字符串)。从itertable中获取字符串必须返回连接:

''.join(filter(str.isalnum, string)) 

或者在连接中传递列表(不确定,但可以快一点)

''.join([*filter(str.isalnum, string)])

注意:unpacking in [*args] valid from Python >= 3.5

function regexFuntion(st) {
  const regx = /[^\w\s]/gi; // allow : [a-zA-Z0-9, space]
  st = st.replace(regx, ''); // remove all data without [a-zA-Z0-9, space]
  st = st.replace(/\s\s+/g, ' '); // remove multiple space

  return st;
}

console.log(regexFuntion('$Hello; # -world--78asdf+-===asdflkj******lkjasdfj67;'));
// Output: Hello world78asdfasdflkjlkjasdfj67

使用翻译:

import string

def clean(instr):
    return instr.translate(None, string.punctuation + ' ')

警告:仅适用于ascii字符串。