简体   繁体   English

正则表达式匹配不需要的字符串

[英]Regular expression matches unwanted strings

I'm trying to fix an issue with a regex replace statement. 我正在尝试使用正则表达式替换语句解决问题。 This is the code: 这是代码:

var str1 = "bbb/mobile-main.min.js";
var str2 = "ttt/main.min.js";
var str21 = "mobile-main.min.js";
var str22 = "main.min.js";


var re = new RegExp("main\.min\.js" + "(\\?[0-9a-z]+)?", "g");

var ans1 = str1.replace(re, '$1main.78765.min.js');

var ans2 = str2.replace(re, '$1main.78765.min.js');

var ans21 = str21.replace(re, '$1main.78765.min.js');

var ans22 = str22.replace(re, '$1main.78765.min.js');

console.log("ans1: "+ ans1);

console.log("ans2: "+ ans2);

console.log("ans21: "+ ans21);

console.log("ans22: "+ ans22);

The result is: 结果是:

   "ans1: bbb/mobile-main.78765.min.js"
   "ans2: ttt/main.78765.min.js"
   "ans21: mobile-main.78765.min.js"
   "ans22: main.78765.min.js"

My desired result is only the second string (str2) to match: 我想要的结果只是要匹配的第二个字符串(str2):

"bbb/mobile-main.min.js"

"ttt/main.78765.min.js"

"mobile-main.min.js"

"main.78765.min.js"

Here is a link to jsbin 这是jsbin的链接

I couldn't find a regular expression statement to match my goal.. Thanks! 我找不到符合我目标的正则表达式语句。谢谢!

Edit : Jsbin link fixed. 编辑 :Jsbin链接已修复。

Another limitation: I will not always have something infront of file's name. 另一个限制:我不会总是在文件名的前面加上一些东西。 This should have similar results (only second should match): 这应该有相似的结果(只有秒应该匹配):

mobile-main.min.js

mail.min.js

Edit2 Edited code + JSBin with all conditions 在所有条件下Edit2编辑代码+ JSBin

You can use this regex: 您可以使用此正则表达式:

var re = new RegExp("(^|/)main\.min\.js" + "(\\?[0-9a-z]+)?", "g");

var ans1 = str1.replace(re, '$1main.78765.min.js'); // bbb/mobile-main.min.js
var ans2 = str2.replace(re, '$1main.78765.min.js'); // ttt/main.78765.min.js

JSBin Demo JSBin演示

(^|/) makes sure that pattern main\\.min\\.js is replaced only when it is at start or preceded by / . (^|/)确保仅在模式main\\.min\\.js开头或之前替换/

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

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