[英]Regex - replace a combination of number and string with another string
I need to replace all occurrence of [any number] and [particular string] with a [replacement string] 我需要用[替换字符串]替换所有出现的[任意数字]和[特定字符串]
For example if strings like 195 apples or 10 apples are found in a paragraph I need to replace this with 10 Oranges 例如,如果在一个段落中找到195个苹果或10个苹果之类的字符串,我需要将其替换为10个橘子
Example paragraph: There are 195 apples in the first basket and 10 apples in the second basket. 示例段落:第一个篮子中有195个苹果,第二个篮子中有10个苹果。
After applying regex replace, I should get a result Result : There are 10 Oranges in the first basket and 10 Oranges in the second basket. 应用正则表达式替换后,我应该得到结果结果:第一个篮子中有10个橙子,第二个篮子中有10个橙子。
In Jquery i used 在我使用的jQuery中
myString.replaceAll("[(?i)string]", "anotherstring");
Need to do this in PHP as well as Jquery. 需要在PHP和Jquery中执行此操作。
Can anyone please help me? 谁能帮帮我吗? Thanks
谢谢
How about: 怎么样:
var myString = 'There are 195 apples in the first basket and 10 apples in the second basket.'; myString = myString.replace("/(?i)\\d+\\s+apples\\b/g", "10 Oranges"); console.log(myString);
Search \\d{1,}\\s+(apples)
搜索
\\d{1,}\\s+(apples)
Replace 10 Oranges
更换
10 Oranges
Try using the following regex : 尝试使用以下正则表达式 :
(\d+\s(\w+))
** you can replace \\w+
with your desired string ** 您可以将
\\w+
替换为所需的字符串
see demo / explanation 见演示/说明
JavaScript 的JavaScript
var str = "There are 195 apples in the first basket and 10 apples in the second basket."; var result = str.replace(/(\\d+\\s(\\w+))/ig, "10 Oranges"); console.log(result);
PHP 的PHP
$re = '/(\d+\s(\w+))/';
$str = 'There are 195 apples in the first basket and 10 apples in the second basket.';
$subst = '10 Oranges';
$result = preg_replace($re, $subst, $str);
echo $result;
This worked 这工作
PHP 的PHP
$re = '/(\d+\s((apples\b|apple\b)+))/';
$str = '195 apples in the first basket and 0 apple but 1 applex';
$subst = '10 Oranges';
$result = preg_replace($re, $subst, $str);
echo $result;
JQuery jQuery查询
var text1 = "10 apples is good";
var rrr = "10 Oranges";
var str = "There are 195 apple in the first basket and 10 apples in the second basket.1 apple";
var result = str.replace(/(\d+\s((apples\b|apple\b)+))/ig,"10 Oranges");
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.