正则表达式检查字符串是否包含某个单词
时间: 2023-09-20 22:06:16 浏览: 53
可以使用正则表达式的`\b`元字符来匹配单词边界,例如:
```python
import re
string = "The quick brown fox jumps over the lazy dog"
word = "fox"
if re.search(rf"\b{word}\b", string):
print(f"{string} contains the word {word}")
else:
print(f"{string} does not contain the word {word}")
```
输出:
```
The quick brown fox jumps over the lazy dog contains the word fox
```
相关问题
正则表达式检查字符串是否包含某个单词,不区分大小写
可以使用以下正则表达式来检查字符串是否包含某个单词,不区分大小写:
```python
import re
word = "apple"
text = "I have an APPLE"
if re.search(r"\b" + re.escape(word) + r"\b", text, flags=re.IGNORECASE):
print("The text contains the word", word)
else:
print("The text does not contain the word", word)
```
解释:
- `\b` 表示单词的边界,确保匹配的是完整的单词,不是单词的一部分。
- `re.escape(word)` 将单词中的特殊字符进行转义,避免正则表达式解析错误。
- `flags=re.IGNORECASE` 表示忽略大小写。
js 正则表达式检查字符串是否包含某个单词,不区分大小写
可以使用正则表达式中的 i 标志来表示不区分大小写,示例代码如下:
```javascript
const string = "This is a string containing the word JavaScript";
const word = "javascript";
const regex = new RegExp(word, "i");
const result = regex.test(string);
console.log(result); // true
```
上述代码中,我们先定义了一个字符串和一个单词,然后使用 RegExp 构造函数创建一个正则表达式对象,其中第二个参数为 "i" 表示不区分大小写。最后使用 test 方法检查字符串中是否包含该单词,返回结果为 true。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![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)