![]() | 1 s 2014-04-15 11:50:58 +08:00 ![]() var ans=[]; str.replace(/Name:\s*([a-z]+)\b/g, function(_, name){ ans.push(name); }); |
![]() | 2 muzuiget 2014-04-15 11:54:43 +08:00 为什么要纠结一条正则,先 split('\n') 然后分两次提取不就好了吗? |
![]() | 3 kfll 2014-04-15 12:06:11 +08:00 ![]() |
![]() | 5 khowarizmi 2014-04-15 12:25:24 +08:00 lss +1 |
![]() | 7 ibudao OP @khowarizmi 恩,那个貌似是正解,不过只能这样曲折了吗。。 |
![]() | 8 jakwings 2014-04-15 12:44:04 +08:00 1 楼的代码差不多了。假如是经常出现这种需求的话,干脆用 YAML 函数库,或者自己写一个简化版通用函数好了。 |
![]() | 9 exoticknight 2014-04-15 12:46:04 +08:00 捕获分组其实是可以的,你只要取[1]分组就可以了 |
![]() | 10 ibudao OP @exoticknight 针对我这个情况,那[1]取分组如何写? |
![]() | 11 rubyking 2014-04-15 15:27:44 +08:00 ![]() 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 2014-04-15 19:22:25 +08:00 via iPhone 使用regexp对象 |
![]() | 15 switch 2014-04-15 21:21:51 +08:00 可以先使用 match 提取出 Name: xxx 后再使用 replace 替换掉 Name: ,如: ``` Str.match(/Name:\s*(\w+)/g) || []).map(function (str) { return str.replace(/Name:\s*/, ""); } ``` match 方法的正则里如果有 g(全局匹配)则分组引用无效了。 |
16 shiye515 2014-04-16 12:01:02 +08:00 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 2014-04-16 12:14:08 +08:00 请原谅我回帖不看之前的回复 `Str.match(/(Name: *).*(?=($|\n))/g).map(function(v){return v.replace(/Name: */,'')}) `这个应该符合要求 |
![]() | 20 s 2014-04-16 17:15:27 +08:00 Str.match(/[^:]+$/mg); |
![]() | 21 exoticknight 2014-04-27 01:04:14 +08:00 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 |