简体   繁体   English

javascript regexp“子字”替换

[英]javascript regexp “subword” replace

I have a phrase like 我有一个像

"everything is changing around me, wonderfull thing+, tthingxx" “我周围的一切都在变化,美好的事物,tthingxx”

and I want to modify every word that contains ***thing at the end of that word, or at most another character after "thing", like "+" or "h" or "x"... 我想修改该单词末尾包含***的每个单词,或者最多修饰“ thing”之后的另一个字符,例如“ +”,“ h”或“ x” ...

something like 就像是

string = 'everything is changing around me, wonderful thing+, tthingxx'
regex = new RegExp('thing(\\+|[g-z])$','g');
string = string.replace(regex, '<b>thing$1</b>');

what I want? 我想要的是? every thing is changing around me, wonderful thing+ , tthingxx 一件事情是我身边的变化,美妙的事+,tthingxx

The result of my regexp? 我的正则表达式的结果? anything working... if I remove the $ all the words containing "thing" and at least another character after it are matched: 任何有效的方法...如果我删除$,则所有包含“ thing”的单词以及匹配后的至少另一个字符:

everything is changing around me, wonderful thing+ , t thingx x 一切都在我身边的变化,美妙的事+,T thingx X

I tryed everything but - in first place I can't understand very well technical english - and second I did't find the answer around. 我尝试了所有方法,但是-首先我听不懂非常熟练的技术英语-其次我没有找到答案。

what I have to do??? 我该怎么办??? thanks in advance 提前致谢


the solution I found was using this regular expression 我发现的解决方案正在使用此正则表达式

/thing([+g-z]){0,1}\b/g

or with the RegExp (I need it because I have to pass a variable): 或使用RegExp(我需要它,因为我必须传递一个变量):

myvar = 'thing';
regex = new RegExp(myvar + "([+g-z]){0,1}\\b" , "g");

I was missing the escape \\ when doing the regular expression in the second mode. 在第二种模式下执行正则表达式时,我缺少了转义\\。 But this isn't enough: the + goes out of the < b > and I don't really know why!!! 但这还不够:+出现在< b >之外 ,我真的不知道为什么!!!


the solution that works as I want is the one by @Qtax: 我想要的解决方案是@Qtax的解决方案:

/thing([+g-z])?(?!\w)/g

thank to the community! 感谢社区!

在正则表达式中使用边界

\b\w+thing(\+|[g-z])?\b

If I understand what you want, then: 如果我了解您的需求,那么:

string = 'everything is changing around me, wonderful thing+, tthingxx';
string = string.replace(/thing(\b|[+g-z]$)/g, '<b>thing$1</b>');

...which results in: ...导致:

every<b>thing</b> is changing around me, wonderful <b>thing</b>+, tthingxx

\\b is a word boundary, so what the regular expression says is anywhere it finds "thing" followed by a word boundary or + or gz at the end of the string, do the replacement. \\b是单词边界,因此正则表达式说的是在找到“事物”的任何位置,后跟单词边界字符串末尾的+gz ,请进行替换。

要解决使用\\b+不匹配的问题,可以使用(?!\\w)代替\\b ,例如:

thing[+g-z]?(?!\w)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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