仅与字母字符匹配的正则表达式变量

Regular expression variable that matches alpha characters only

本文关键字:正则表达式 变量 字符      更新时间:2023-09-26

我有这个不起作用的javascript:

function test(id) {
    if (id.match('^(.+?)#')) {
        alert(RegExp.$1);   
    }
}
test('test#f');   // should alert 'test'
test('tes4t#f');  // should not alert

http://jsfiddle.net/r7mky2y9/1/

我只想匹配出现在#之前a-zA-Z字符。我尝试调整正则表达式,使其(.+?)[a-zA-Z]但我有一种不正确的感觉。

这是您的正则表达式 101:

var m = id.match(/^([a-zA-Z]+)#/);
if (m) alert(m[1]);

在 Javascript 中,正则表达式是在斜杠之间定义的。

此外,惰性量词在这里没有用。我没有测试过性能,但应该没有任何区别。

最后,利用 match 的返回值,该值返回具有完整数学表达式的数组,后跟捕获的组。

试试这个:

function test(id) {
  var rmatch = /^([a-zA-Z]+?)#/;
  var match = id.match(rmatch);
  if (match) {
    alert(match[1]);
  }
}

解释:

function test(id) {
  var rmatch = /^([a-zA-Z]+?)#/; // This constructs a regex, notice it is NOT a string literal
  // Gets the match followed by the various capture groups, or null if no match was found
  var match = id.match(rmatch);
  if (match) {
    // match[1] is the first capture group, alert that
    alert(match[1]);
  }
}

试试这个:

function test(id) {
  var regex = /([a-z]+)#/i,
      group = regex.exec(id);
  if (group && group[1]) {
    alert(group[1]);
  }
}

它说捕获(带有parens)一组一个或多个字母([a-z]+),后跟一个哈希,并使匹配不区分大小写(因为末尾的i)。

使用 if(id.match(/^([a-zA-Z]+)#/))

更新了我的答案,因为match需要一个正则表达式参数,而不是字符串。

此外,出于某种原因,id.match(/^([A-z]+)#/)匹配^test。为什么?