简体   繁体   English

正则表达式匹配两个字符串之间的数字不适用于JS

[英]Regex match digits between two strings not working in JS

I have a regex which is working fine in regex101 but not in javascript/jquery, I think because of the ?<= expression. 我有一个正则表达式,可以在regex101中正常工作,但在javascript / jquery中却不能,我认为是因为?<=表达式。 If I omit this part, it works, but replaces the preceding string as well. 如果我省略了这一部分,那么它会起作用,但也会替换前面的字符串。 I want to replace only the digits in the URL, or in other words all digits between "foo/" and "/bar" 我只想替换URL中的数字,换句话说,就是“ foo /”和“ / bar”之间的所有数字。

My code: 我的代码:

<a id="link" href="http://www.domain.com/foo/1234/bar/">Some anchor text</a>
<button>Click</button>

$("button").click(function() {
  $('#link').attr('href', function(index, myhref) {
    return myhref.replace(/(?<=foo\/)(\d+)(?=\/bar)/,'newnumber');
   });
});

How do I have to modify my regex so that it replaces the digits? 我该如何修改我的正则表达式,使其替换数字?

Correct, it's because look-behinds aren't supported in JavaScript. 正确,这是因为JavaScript不支持回溯。 Instead you could use an output string that includes the prefix and suffix: 相反,您可以使用包含前缀和后缀的输出字符串:

return myhref.replace(/foo\/\d+\/bar/,'foo/newnumber/bar');

If newnumber is a variable, use concatenation: 如果newnumber是变量,请使用串联:

return myhref.replace(/foo\/\d+\/bar/,'foo/' + newnumber + '/bar');

JavaScript doesn't support positive or negative lookbehind. JavaScript不支持正向或负向后退。 But, you might want to try to capture its group and use them as you're replacing the string. 但是,您可能想尝试捕获其组并在替换字符串时使用它们。

Eg 例如

var str = 'http://www.domain.com/foo/1234/bar/';
var myvar = 'newnumber';
var newStr = str.replace(/(foo\/)(\d+)(\/bar)/i, '$1' + myvar + '$3');
// Returns "http://www.domain.com/foo/newnumber/bar/"
  • (foo\\/) is the first group, matching foo/ (foo\\/)是第一组,匹配foo/
  • (\\d+) is the second group, matching any digits number for one or more. (\\d+)是第二组,匹配任何一个或多个数字。
  • (\\/bar) is the third group, matching /bar (\\/bar)是第三组,匹配/bar
  • '$1'+ myvar +'$3' returns a concat of first group + myvar + third group '$1'+ myvar +'$3'返回first group + myvar + third group

you could use: 您可以使用:

myhref.replace(new RegExp("\/[0-9]*\/", "g"), "/newnumber/")

EDIT: if you want to replace the number by a "newnumber" only if it is between foo and bar then you should add those at RegExp as well as follows. 编辑:如果仅当它在foobar之间时,如果要用“ newnumber”替换数字,则应在RegExp处添加它们,如下所示。 The code above is going to replace the number without verifying it. 上面的代码将替换数字而不进行验证。

myhref.replace(new RegExp("foo\/[0-9]*\/bar", "g"), "foo/newnumber/bar")

You can use .match() with RegExp /\\d+/ to match digits in string, .replace() matched digits with newnumber 您可以将.match()RegExp /\\d+/配合使用以匹配字符串中的数字,将.replace()匹配的数字与newnumber匹配

var str = "http://www.domain.com/foo/1234/bar/";
var newnumber = 5678;
var n = str.match(/\d+/)[0];
str = str.replace(n, newnumber);

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

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