简体   繁体   English

正则表达式更改字符串中的某些单词

[英]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 (见下文),我想更换,是不是任何字shadegravelgravel

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])匹配非gravel|任意一个字符并将其捕获到组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) -否定的超前行为,将排除匹配整个单词的shadegravel
  • \\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/joinarray.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM