js正则假设有一个多字符的片断重复出现,把"really"、"really really ",以及任意数量连续出现的"really"字符串换成一个简单的"very ” ( Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard )
时间: 2023-07-13 18:09:51 浏览: 97
可以使用正则表达式和replace方法来实现:
```javascript
const str = "Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard";
const newStr = str.replace(/(really\s+)+/g, "very ");
console.log(newStr);
```
输出结果为:"Billy tried very hard Sally tried very hard Timmy tried very hard Johnny tried very hard"。
解释一下正则表达式的含义:
- `(really\s+)+`:匹配一个或多个重复出现的"really"字符串,每个字符串后面可能跟着一个或多个空格。
- `/g`:全局匹配模式,表示匹配所有符合模式的字符串。
- `"very "`:将匹配到的字符串替换成"very "。
相关问题
在js中使用正则假设有一个多字符的片断重复出现,把"really"、"really really ",以及任意数量连续出现的"really"字符串换成一个简单的"very ” ( Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard )
你可以使用正则表达式和 replace() 方法来完成这个任务。下面是代码示例:
```javascript
const str = "Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard";
const result = str.replace(/really +/g, "very ");
console.log(result);
```
输出结果为:
```
Billy tried very hard Sally tried very hard Timmy tried very hard Johnny tried very hard
```
正则表达式 /really +/g 匹配一个或多个空格后面紧跟着 "really" 的字符串,并且全局匹配所有这样的字符串。replace() 方法将匹配到的字符串替换为 "very "。
正则假设有一个多字符的片断重复出现,把"really"、"really really ",以及任意数量连续出现的"really"字符串换成一个简单的"very ” ( Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard )
可以使用正则表达式来实现这个替换操作,具体方法如下:
1. 使用正则表达式匹配多个连续的"really"字符串,可以使用正则表达式"\b(really\s+){2,}\b",其中"\b"表示单词边界,"\s+"表示一个或多个空格。
2. 将匹配到的字符串替换为"very ",可以使用字符串的replace方法,将匹配到的字符串替换为"very "即可。
完整代码如下:
```python
import re
s = "Billy tried really hard Sally tried really really hard Timmy tried really really really hard Johnny tried really really really really hard"
# 使用正则表达式匹配多个连续的"really"字符串
pattern = r'\b(really\s+){2,}\b'
result = re.sub(pattern, 'very ', s)
print(result)
```
输出结果为:"Billy tried very hard Sally tried very hard Timmy tried very hard Johnny tried very hard"。
阅读全文