
1 s Apr 15, 2014 var ans=[]; str.replace(/Name:\s*([a-z]+)\b/g, function(_, name){ ans.push(name); }); |
2 muzuiget Apr 15, 2014 为什么要纠结一条正则,先 split('\n') 然后分两次提取不就好了吗? |
5 khowarizmi Apr 15, 2014 lss +1 |
7 ibudao OP @khowarizmi 恩,那个貌似是正解,不过只能这样曲折了吗。。 |
8 jakwings Apr 15, 2014 1 楼的代码差不多了。假如是经常出现这种需求的话,干脆用 YAML 函数库,或者自己写一个简化版通用函数好了。 |
9 exoticknight Apr 15, 2014 捕获分组其实是可以的,你只要取[1]分组就可以了 |
10 ibudao OP @exoticknight 针对我这个情况,那[1]取分组如何写? |
11 rubyking Apr 15, 2014 Str.match(/\w+$/mg); |
12 ibudao OP 实际上我的源string是这样的: Available Android Virtual Devices: Name: test Path: /home/kingbo/.android/avd/test.avd Target: Android 4.4 (API level 19) ABI: armeabi-v7a Skin: WVGA800 --------- Name: ects Path: /home/kingbo/.android/avd/ects.avd Target: Android 4.4 (API level 19) ABI: armeabi-v7a Skin: WVGA800 |
14 xu33 Apr 15, 2014 via iPhone 使用regexp对象 |
15 switch Apr 15, 2014 可以先使用 match 提取出 Name: xxx 后再使用 replace 替换掉 Name: ,如: ``` Str.match(/Name:\s*(\w+)/g) || []).map(function (str) { return str.replace(/Name:\s*/, ""); } ``` match 方法的正则里如果有 g(全局匹配)则分组引用无效了。 |
16 shiye515 Apr 16, 2014 Str.match(/(: *).*(?=($|\n))/g).map(function(v){return v.replace(/: */,'')}),现学现卖,参考http://deerchao.net/tutorials/regex/regex.htm , http://www.cnblogs.com/rubylouvre/archive/2010/03/09/1681222.html ,Javascript不支持后瞻,要不后面的map都可以省了 |
18 shiye515 Apr 16, 2014 请原谅我回帖不看之前的回复 `Str.match(/(Name: *).*(?=($|\n))/g).map(function(v){return v.replace(/Name: */,'')}) `这个应该符合要求 |
20 s Apr 16, 2014 Str.match(/[^:]+$/mg); |
21 exoticknight Apr 27, 2014 v2ex的提醒系统完全没提示…… var re = /Name:\s*([a-z]+\b)/g,match; match = re.exec( Str ); while ( match != null ) { console.log( match[1] ); // or whatever else match = re.exec( Str ); } @ibudao |