简体   繁体   English

Javascript - 带有字符串模板后跟 4 位数字的正则表达式?

[英]Javascript - Regular Expression with string template followed by 4 digits number?

Good day.再会。 I wanna detect the url string in the <a> tag我想检测<a>标签中的 url 字符串

<a href="http://virtualweb.test/en/?post_type=tribe_events&p=3642">Link</a>

whether it matchs the pattern : ?post_type=tribe_events&p=#### (#### = 4 digits number)是否匹配模式: ?post_type=tribe_events&p=#### (#### = 4 位数字)

I'm writing some Jquery code to detect the expression but the console is throwing the error :我正在编写一些 Jquery 代码来检测表达式,但控制台抛出错误:

Invalid regular expression: /^(?)post_type=tribe_events&p=^(d{4})/: Invalid group无效正则表达式:/^(?)post_type=tribe_events&p=^(d{4})/:无效组

var str = $(a).attr("href");
var regexEx  = /^(?)post_type=tribe_events&p=^(d{4})/;
  var ok = regexEx.exec(str);
  console.log(ok);

I'm not good at the regex so I'd be aprreciated if there's any help.我不擅长正则表达式,所以如果有任何帮助,我会很感激。

There are couple of issues in your regex.您的正则表达式中有几个问题。

  • You need to remove ^ from your regex which denotes start of string and in your case your string doesn't actually start from a ?您需要从正则表达式中删除^ ,它表示字符串的开头,在您的情况下,您的字符串实际上并不是从? and is in middle of the string.并且在字符串的中间。
  • You need to escape ?你需要逃跑? as it has special meaning in regex which is zero or one occurrence of a character.因为它在正则表达式中具有特殊含义,即字符出现零次或一次。
  • You need to remove second ^ after p= which isn't needed您需要在不需要的p=之后删除第二个^
  • You need to write \\d and not just d for representing a number.你需要写\\d而不仅仅是d来表示一个数字。
  • Also you don't need to group ?你也不需要分组? and \\d{4} unless you really need them.\\d{4}除非你真的需要它们。

You corrected regex becomes,你更正了正则表达式,

\?post_type=tribe_events&p=\d{4}

Demo演示

如果测试真的是你想要的,我想正确的语法是:

/^\?post_type=tribe_events&p=\d{4}/

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

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