正则去掉标点符号和空格
时间: 2023-10-12 13:09:32 浏览: 45
可以使用正则表达式来去掉标点符号和空格。以下是一个示例代码:
```python
import re
text = "Hello, world! This is a test text."
# 去掉标点符号和空格
processed_text = re.sub(r'[^\w\s]', '', text).replace(' ', '')
print(processed_text)
```
输出结果为:
```
HelloworldThisisatesttext
```
其中,正则表达式 `[^\w\s]` 匹配除了字母、数字和空格以外的任何字符,然后使用 `re.sub()` 函数将其替换为空字符串。接着使用 `.replace()` 函数将空格替换为空字符串,从而去掉所有的空格。
相关问题
用正则表达式去除标点符号
可以使用以下正则表达式去除标点符号:
```python
import re
text = "Hello, world! This is a sentence."
cleaned_text = re.sub(r'[^\w\s]', '', text)
print(cleaned_text)
```
输出:
```
Hello world This is a sentence
```
正则表达式 `[^\w\s]` 匹配非单词字符和非空格字符,即标点符号。使用 `re.sub()` 函数可以将匹配到的字符替换为空字符串。
python 正则表达式 除标点符号以外
以下是使用Python正则表达式除去标点符号的示例:
```python
import re
text = "Hello, world! This is a sentence with punctuation."
# 使用正则表达式除去标点符号
clean_text = re.sub(r'[^\w\s]', '', text)
print(clean_text) # 输出:Hello world This is a sentence with punctuation
```
在上面的示例中,我们使用`re.sub()`函数来替换字符串中的标点符号。正则表达式`[^\w\s]`表示匹配除了字母、数字、下划线和空格之外的任何字符。通过将匹配到的字符替换为空字符串,我们可以将标点符号从字符串中去除。