简体   繁体   English

使用JavaScript正则表达式删除'&&&'之后的字符串的最后一部分

[英]remove last part of string following '&&&' with JavaScript Regex

I'm trying to use a regex in JS to remove the last part of a string. 我正在尝试在JS中使用正则表达式来删除字符串的最后一部分。 This substring starts with &&& , is followed by something not &&& , and ends with .pdf . 该子字符串以&&&开头,后跟不是&&& ,并以.pdf结尾。

So, for example, the final regex should take a string like: 因此,例如,最终的正则表达式应采用类似以下的字符串:

parent&&&child&&&grandchild.pdf

and match 并匹配

parent&&&child

I'm not that great with regex's, so my best effort has been something like: 我对regex不太满意,所以我最大的努力就是:

.*?(?:&&&.*\.pdf)

Which matches the whole string. 匹配整个字符串。 Can anyone help me out? 谁能帮我吗?

You may use this greedy regex either in replace or in match : 您可以在replacematch使用此贪婪的正则表达式:

 var s = 'parent&&&child&&&grandchild.pdf'; // using replace var r = s.replace(/(.*)&&&.*\\.pdf$/, '$1'); console.log(r); //=> parent&&&child // using match var m = s.match(/(.*)&&&.*\\.pdf$/) if (m) { console.log(m[1]); //=> parent&&&child } 

By using greedy pattern .* before &&& we make sure to match **last instance of &&& in input. 通过在&&&之前使用贪婪模式 .* ,我们确保匹配**输入中&&&最后一个实例。

You want to remove the last portion, so replace it 您要删除最后一部分,所以将其替换

 var str = "parent&&&child&&&grandchild.pdf" var result = str.replace(/&&&[^&]+\\.pdf$/, '') console.log(result) 

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

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