听起来很容易,但我无法弄明白。
/([a-z][a-z0-9]+)/gi
测试用例看起来像这样
Correct #123 2baZ #1a2 thisToo $bar andTwo2
我正在与那些局部比赛作战。唯一有效的应该是:["Correct", "thisToo", "andTwo2"]
。任何其他人应该保持无与伦比。
以下是测试人员的链接:http://regex101.com/r/qG7lU9/8
更新:
这是JS小提琴,它比测试者本身更好... http://jsfiddle.net/FredyCr/6hsgef82/
答案 0 :(得分:1)
从组索引2中获取匹配的字符串。
(?:^| )([a-z][a-z0-9]+)(?: |$)
Javascript代码将是,
> var re = /(?:^| )([a-z][a-z0-9]+)(?: |$)/gi
undefined
> var str = " Correct #123 2baZ #1a2 thisToo $bar andTwo2";
undefined
> var matches = [];
undefined
> while (match = re.exec(str))
... {
... matches.push(match[1]);
... }
3
> console.log(matches);
[ 'Correct', 'thisToo', 'andTwo2' ]
答案 1 :(得分:1)
您可以使用基于前瞻和非捕获组的正则表达式:
(?:^| )([a-z][a-z0-9]+(?= |$))
并使用捕获的组#1进行匹配:
Correct
thisToo
andTwo2
<强>代码:强>
var rx = /(?:^| )([a-z][a-z0-9]+(?= |$))/gi
var str = " Correct #123 2baZ #1a2 thisToo $bar andTwo2";
var matches = [];
while (match = rx.exec(str))
matches.push(match[1]);
console.log(matches);
//=> ["Correct", "thisToo", "andTwo2"]
答案 2 :(得分:1)
var regex = /(^|\s)[a-z][a-z0-9]+/gi;
var text = "Correct #123 2baZ #1a2 thisToo $bar andTwo2";
var found;
while ((found = regex.exec(text)) !== null)
console.log(found[0].trim());
输出
Correct
thisToo
andTwo2
答案 3 :(得分:0)
解决方法:拆分并过滤所需的标记:
var rx = /^[a-zA-Z][a-zA-Z0-9]*$/;
var match = str.split(/\s+/).filter(rx.exec.bind(rx));