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


当前回答

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

其他回答

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

例如德语:

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

字符串。标点符号包含以下字符:

'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'

可以使用translate和maketrans函数将标点符号映射为空值(替换)

import string

'This, is. A test!'.translate(str.maketrans('', '', string.punctuation))

输出:

'This is A test'
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

这可以不使用regex完成:

>>> string = "Special $#! characters   spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'

你可以使用str.isalnum:

S.isalnum() -> bool 如果S中的所有字符都是字母数字,则返回True 且S中至少有一个字符,否则为假。

如果坚持使用正则表达式,其他解决方案也可以。但是请注意,如果可以在不使用正则表达式的情况下完成,那么这是最好的方法。

假设你想要使用正则表达式并且你想要/需要unicode - cognant 2。X代码是2to3-ready:

>>> import re
>>> rx = re.compile(u'[\W_]+', re.UNICODE)
>>> data = u''.join(unichr(i) for i in range(256))
>>> rx.sub(u'', data)
u'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\xaa\xb2 [snip] \xfe\xff'
>>>