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


当前回答

import re
abc = "askhnl#$%askdjalsdk"
ddd = abc.replace("#$%","")
print (ddd)

你会看到你的结果是

'Askhnlaskdjalsdk

其他回答

与使用正则表达式的其他人不同,我将尝试排除不是我想要的每个字符,而不是显式地列举我不想要的字符。

例如,如果我只想要字符从'a到z'(大写和小写)和数字,我将排除所有其他:

import re
s = re.sub(r"[^a-zA-Z0-9]","",s)

这意味着“用空字符串替换每个不是数字的字符,或者'a到z'或'a到z'范围内的字符”。

事实上,如果你在正则表达式的第一个位置插入特殊字符^,你将得到否定。

额外提示:如果您还需要将结果小写,您可以使正则表达式更快更简单,只要您现在不会发现任何大写。

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

最通用的方法是使用unicodedata表的“类别”,它对每个字符进行分类。例如,下面的代码只过滤基于类别的可打印字符:

import unicodedata
# strip of crap characters (based on the Unicode database
# categorization:
# http://www.sql-und-xml.de/unicode-database/#kategorien

PRINTABLE = set(('Lu', 'Ll', 'Nd', 'Zs'))

def filter_non_printable(s):
    result = []
    ws_last = False
    for c in s:
        c = unicodedata.category(c) in PRINTABLE and c or u'#'
        result.append(c)
    return u''.join(result).replace(u'#', u' ')

查看上面给出的所有相关类别的URL。当然你也可以过滤 按标点符号分类。

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 re
my_string = """Strings are amongst the most popular data types in Python. We can create the strings by enclosing characters in quotes. Python treats single quotes the 

和双引号一样。”""

# if we need to count the word python that ends with or without ',' or '.' at end

count = 0
for i in text:
    if i.endswith("."):
        text[count] = re.sub("^([a-z]+)(.)?$", r"\1", i)
    count += 1
print("The count of Python : ", text.count("python"))