我正在尝试在网址中查找2位数字符串。例如:
www.abc.com/ff_gg/abc
我可以查看:
if (window.location.href.indexOf("ff_gg") > -1) {
//
} else ...
但 ff _ gg 可以是随机字符串。如何使用正则表达式将{ur}中的ff
和gg
保存为变量? ff
和gg
将由_
分开。
答案 0 :(得分:3)
您可以将String#search
与正则表达式一起使用,而不是String#indexOf
。或RegExp#test
另见RegExp
了解表达方式。
class base
{
public:
template<class T> int func();
// ^^^^^
// use class keyword
}; // <-- semicolon here
template<class T>
// ^^^^^
// use class keyword
int base::func()
{
return 0;
}
class derived : public base
// ^
// no colon here
{
void caller()
{
func<int>(); // it works
base::func<int>(); // this works too
}
}; // <-- semicolon here
你可以使用类似的正则表达式String#match
并捕获,或RegExp#exec
。
或者使用String#split
或String#slice
进行字符串操作。
如您所见,有几个选项(甚至更多我没有提及的选项),但我现在没有时间为每个选项创建一个示例。
const text = 'www.abc.com/ff_gg/abc';
const rx = /\/[a-z]{2}_[a-z]{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');
}
const text = 'www.abc.com/ff_gg/abc';
const match = text.match(/\/([a-z]{2})_([a-z]{2})\//i);
if (match) {
console.log(match);
}
答案 1 :(得分:1)
答案 2 :(得分:1)
在javascript中,您可以制作RegExp
对象。有关RegExp
对象的详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
以下示例应该有效:
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");
}
&#13;
以下是正则表达式的示例:http://regexr.com/3e8a7