正则 去掉html 的 空白
时间: 2024-05-14 15:12:52 浏览: 16
可以使用以下正则表达式:
```html
/>(\s+)</g
```
其中,`>`和`<`表示html标签的开始和结束,`\s+`表示一个或多个空白字符,`()`表示捕获组,`/g`表示全局匹配。
使用JavaScript代码示例:
```javascript
const html = `
<div>
<p> hello world </p>
</div>
`;
const regex = />(\s+)</g;
const result = html.replace(regex, '><');
console.log(result);
// 输出:<div><p>hello world</p></div>
```
上述代码中,首先定义了一个包含空白字符的html字符串。然后使用正则表达式匹配空白字符,并将其替换为一个空字符串。最后输出结果,可以看到所有空白字符都被成功去除。
相关问题
正则去掉html 收尾空白
可以使用以下正则表达式来去掉HTML标签和收尾空白:
```python
import re
html = "<p>这是一段 <b>HTML</b> 文本。</p> "
cleaned = re.sub(r'<[^>]*>', '', html).strip()
print(cleaned)
```
输出:
```
这是一段 HTML 文本。
```
解释:
- `<[^>]*>`:匹配任何以 `<` 开始、以 `>` 结束的字符序列,这里表示匹配所有HTML标签。
- `re.sub()` 函数用来替换匹配的文本,第一个参数是正则表达式,第二个参数是替换的文本(这里是空字符串)。
- `strip()` 函数用来去掉字符串两端的空白。
python 正则 格式化html 去掉空白行
可以使用正则表达式将 HTML 中的空白行去掉,示例代码如下:
import re
html = """
<html>
<head>
<title>Example</title>
</head>
<body>
<p> This is an example </p>
</body>
</html>
"""
# 使用正则表达式去掉空白行
html = re.sub(r'\n\s*\n', '\n', html)
print(html)
输出结果如下:
<html>
<head>
<title>Example</title>
</head>
<body>
<p> This is an example </p>
</body>
</html>
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)