[英]regex to change certain words in a string
I am trying to get my head around regular expressions. 我正在设法使我对正则表达式有所了解。 I thought the following would work, but unfortunately it isn't.
我以为以下方法会起作用,但不幸的是,它不会起作用。
What I want to do: 我想做的事:
Given a string str
(see below) I want to replace any word that is not shade
or gravel
with the word gravel
. 给定一个字符串
str
(见下文),我想更换,是不是任何字shade
或gravel
字gravel
。
str = "gravel shade water grass people water shade";
output = str.replace(/([^gravel|^shade])/g,' gravel ');
output
should equal gravel shade gravel gravel gravel gravel shade
. gravel shade gravel gravel gravel gravel shade
output
应等于gravel shade gravel gravel gravel gravel shade
。 What I have is close enough but a bit off. 我所拥有的足够接近,但有点偏离。
Your ([^gravel|^shade])
matches and captures into Group 1 any one single character that is not g
, r
, a
, v
, e
, l
, |
您的
([^gravel|^shade])
匹配非g
, r
, a
, v
, e
, l
, |
任意一个字符并将其捕获到组1中|
, ^
, and replace all of them with gravel
. ,
^
,然后全部用gravel
代替。
You can use 您可以使用
/\b(?!(?:shade|gravel)\b)\w+\b/g
See the regex demo 见正则表达式演示
Pattern description: 模式说明:
\\b
- leading word boundary \\b
前导词边界 (?!(?:shade|gravel)\\b)
- a negative lookahead that will exclude matching whole words shade
and gravel
(?!(?:shade|gravel)\\b)
-否定的超前行为,将排除匹配整个单词的shade
和gravel
\\w+
- 1+ word characters (belonging to the [A-Za-z0-9_]
set) \\w+
-1个以上的文字字符(属于[A-Za-z0-9_]
设置) \\b
- trailing word boundary. \\b
尾部单词边界。 var str = 'gravel shade water grass people water shade'; var result = str.replace(/\\b(?!(?:shade|gravel)\\b)\\w+\\b/g, 'gravel'); document.body.innerHTML = result;
Here is a non-regex solution for your problem using split/join
and array.map
: 这是使用
split/join
和array.map
的非正则表达式解决方案:
var str = "gravel shade water grass people water shade"; var repl = str.split(' ').map(function (w) { return (w!='gravel' && w!= 'shade')?'gravel':w; }).join(' ') document.writeln("<pre>" + repl + "</pre>") //=> "gravel shade gravel gravel gravel gravel shade"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.