我需要从字符串中删除所有特殊字符,标点符号和空格,以便我只有字母和数字。
当前回答
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'
>>>
推荐文章
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- defaultdict的嵌套defaultdict
- 构造tkinter应用程序的最佳方法?
- 如何在Python中逐行打印字典?
- 当试图运行Python脚本时,“ImportError:没有命名模块”
- pylab和pyplot的区别是什么?
- Argparse:确定使用了哪个子解析器
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 如何从JavaScript中使用正则表达式的字符串中剥离所有标点符号?
- Ruby数组到字符串的转换
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 正则表达式中的单词边界是什么?