简体   繁体   English

正则表达式javascript如何检查aa_bb

[英]Regular Expressions javascript how to check aa_bb

I'm trying to look for 2 digit string in URL. 我正在尝试在URL中查找2位数字的字符串。 For example: 例如:

www.abc.com/ff_gg/abc

I can check it with: 我可以用以下方法检查它:

if (window.location.href.indexOf("ff_gg") > -1) {
    // 
} else ...

but ff _ gg can be a random string. 但是ff _ gg可以是随机字符串。 How to use regex to save ff and gg from a url as a variable ? 如何使用正则表达式将ff gggg保存为变量? ff and gg will be separated by _ . ffgg将以_分隔。

You can use String#search with a regex, instead of String#indexOf . 您可以使用带有正则表达式的String#search ,而不是String#indexOf Or RegExp#test RegExp#test

Also see RegExp to understand the expression. 另请参阅RegExp了解表达式。

 const text = 'www.abc.com/ff_gg/abc'; const rx = /\\/[az]{2}_[az]{2}\\//i; if (text.search(rx) > -1) { console.log('found'); } else { console.log('not found'); } if (rx.test(text)) { console.log('found'); } else { console.log('not found'); } 

You could use a similar regex to String#match and capture, or RegExp#exec . 您可以使用类似于String#match和capture的regex或RegExp#exec

Alternatively use string manipulation with String#split or String#slice . 或者使用String#splitString#slice字符串操作。

As you see, there are several options (and even more that I've not mentioned) but I don't have time just now to create an example for each. 如您所见,有多个选项(甚至还有更多我没有提到的选项),但是我现在没有时间为每个选项创建示例。

 const text = 'www.abc.com/ff_gg/abc'; const match = text.match(/\\/([az]{2})_([az]{2})\\//i); if (match) { console.log(match); } 

 const text = 'www.abc.com/ff_gg/abc'; const rx = /\\/[az]{2}_[az]{2}\\//i; const index = text.search(rx); if (index > -1) { console.log(text.slice(index + 1, index + 1 + 5).split('_')); } 

([a-zA-Z]{2})_([a-zA-Z]{2})

2 capturing groups separated by _ can do the trick for the regex. 用_分隔的2个捕获组可以完成正则表达式。

Then use match() who will return the matched groups 然后使用match()将返回匹配的组

demo 演示

In javascript you can make a RegExp object. 在javascript中,您可以创建RegExp对象。 For more information about the RegExp object see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions 有关RegExp对象的更多信息,请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

The following example should work: 下面的示例应该起作用:

 var url = "www.abc.com/ff_gg/abc"; var reg = new RegExp("([a-zA-Z]{2})_([a-zA-Z]{2})"); if (reg.test(url)) { var matches = url.match(reg); var ff = matches[1]; var gg = matches[2]; console.log("group1: " + ff); console.log("group2: " + gg); console.log("do something"); } 

Here is also a example of the regex: http://regexr.com/3e8a7 这也是正则表达式的示例: http : //regexr.com/3e8a7

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

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