在Python中组合正则表达式-\ W和\ S

时间:2019-05-19 16:44:17

标签: python regex string

我希望我的代码仅返回特殊字符[".", "*", "=", ","] 我要删除所有数字/字母字符("\W")和所有空白("\S")

import re

original_string = "John is happy. He owns 3*4=12, apples"
new_string = re.findall("\W\S",original_string)
print(new_string)

但是我将其作为输出: [' i', ' h', ' H', ' o', ' 3', '*4', '=1', ' a']

我绝对不知道为什么会这样。因此,我有两个问题:

1)使用正则表达式是否可以实现我的目标

2)我的代码实际上在做什么?

3 个答案:

答案 0 :(得分:3)

您已经接近了,但是您需要在角色类中指定这些转义序列。

re.findall(r'[^\w\s]', original_string)
# ['.', '*', '=', ',']

请注意,插入符号^表示否定(即匹配这些字符)。

或者,不删除不需要的内容,为什么不提取您的操作呢?

re.findall(r'[.*=,]', original_string)
# ['.', '*', '=', ',']

答案 1 :(得分:2)

在这里,我们还可以在[]中添加所需的特殊字符,然后轻扫其他所有内容,然后仅收集这些字符:

([\s\S].*?)([.*=,])?

Python测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([\s\S].*?)([.*=,])?"

test_str = "John is happy. He owns 3*4=12, apples"

subst = "\\2"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

JavaScript演示

const regex = /([\s\S].*?)([.*=,])?/gm;
const str = `John is happy. He owns 3*4=12, apples`;
const subst = `$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

RegEx

如果这不是我们想要的表达式,我们可以在regex101.com中对其进行修改/更改。

enter image description here

RegEx电路

我们还可以可视化jex.im中的表达式:

enter image description here

Demo

答案 2 :(得分:1)

正则表达式\W\S匹配两个字符的序列;一个非单词,一个非空格。如果要组合它们,那就是[^\w\s],它与一个不属于单词或空白组的字符匹配。

但是,有许多字符不是您枚举的与该表达式匹配的字符之一。如果要删除不在集合中的字符,则包含所有这些字符的字符类就是[^.*=,]

也许值得一提的是,在[...]中,您不需要(实际上也不需要)例如反斜杠转义。文字点。默认情况下,字符类不能与换行符匹配,尽管可以使用选项re.DOTALL进行更改。

如果您试图提取和解析数字表达式,则正则表达式可能是词法分析中有用的一部分,但您确实需要一个合适的解析器。

相关问题