简体   繁体   English

正则表达式只替换匹配的一部分

[英]regex replace only a part of the match

I want to replace only a part of the string of a regex pattern match. 我想只替换正则表达式模式匹配的一部分字符串。 I found this answer but I don't get it... 我找到了这个答案,但我没有得到它......
How do I use substitution? 我如何使用替代?

Example of what I want: keep the first slug digit, only replace others 我想要的例子:保留第一个slug数字,只替换其他数字

/09/small_image/09x/ > /09/thumbnail/ /09/small_image/09x/ > /09/thumbnail/
1st: unknown digit 第1名: unknown digit
2nd: "small_image" 第二名: "small_image"
3rd: unknown digit + "x" 第3名: unknown digit + "x"

Here is what I have so far: 这是我到目前为止:

var regexPattern = /\/\d\/small\_image\/\d*x/;
var regexPattern = /\/\d\/(small\_image\/\d*x)$1/;  ??

var result = regexPattern.test(str);
if (result) {
  str = str.replace(regexPattern, 'thumbnail');
}

 var input = "/09/small_image/09x/"; var output = input.replace(/(\\/\\d+\\/)small_image\\/\\d*x/, "$1thumbnail"); console.log(output); 

Explanation: 说明:

Put the part you want to keep in parentheses, then refer to that as $1 in the replacement string - don't put $1 in your regex. 把你想要保留的部分放在括号中,然后在替换字符串中将其称为$1 - 不要在你的正则表达式中$1 So (\\/\\d+\\/) means to match a forward slash followed by one or more digits, followed by another forward slash. 所以(\\/\\d+\\/)表示匹配正斜杠后跟一个或多个数字,后跟另一个正斜杠。

(Note that you don't need to escape underscores in a regex.) (请注意,您不需要在正则表达式中转义下划线。)

Go with 跟着去

var regexPattern = /(\/\d+\/)small\_image\/\d*x/;

and

str = str.replace(regexPattern, '$1thumbnail');

First , you were missing the + . 首先 ,你错过了+ Because 09 are two digits, you need the regexp to match one or more digits ( \\ḑ would be exactly one). 因为09是两位数,所以你需要正则表达式来匹配一个或多个数字( \\ḑ就是一个数字)。 This is accomplished by \\d+ 这是通过\\d+完成的
Second , everything you match is being removed at first. 其次 ,首先要删除你匹配的所有内容。 To get the /09/ part back afterwards, you have to remember it by putting it into brackets in the regexp ( ... ) and afterwards reference it in the replacement via $1 要在之后恢复/09/部分,您必须通过将其放入正则表达式( ... )中的括号中来记住它,然后通过$1在替换中引用它
One could as well create other groups and reference them by $2 , $3 ... 还可以创建其他组,并以$2 $3 $2引用它们......

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

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