简体   繁体   中英

javascript regexp find multiple match between two string

How do I write a regular expression in javascript such that it parses the string "1.aaa 2.bbb 3.ccc" into ["aaa","bbb","ccc"] .

here is my code :

 var str = "1.aaa 2.bbb 3.ccc"; var reg1 = /\\d+\\.(.*)\\d+\\./g; //sub regexp $1 match "aaa 2.bbb" var reg2 = /\\d+\\.(.*?)\\d+\\./g; //sub regexp $1 match "aaa" var reg3 = /\\d+\\.(.*?)(?=\\d+\\.)/g; //sub regexp $1 match "aaa" 、 "bbb" var reg4 = /\\d+\\.(.*?)(?=\\d+\\.)|\\d+\\.(.*)/g; //sub regexp $1 match "aaa" 、 "bbb"、undefined,my expect is $1 match "aaa"、“bbb”、“ccc” str.replace(reg1, function(match, p1, p2, offset, string) { console.log("---reg1---") console.log(p1) }) str.replace(reg2, function(match, p1, p2, offset, string) { console.log("---reg2---") console.log(p1) }) str.replace(reg3, function(match, p1, p2, offset, string) { console.log("---reg3---") console.log(p1) }) str.replace(reg4, function(match, p1, p2, offset, string) { console.log("---reg4---") console.log(p1) //sub regexp $1 match "aaa" 、 "bbb"、undefined,my expect is $1 match "aaa"、“bbb”、“ccc” }) 

Is there a simple solution to do this?

Since you didn't give much information this is the best I can come up with.

 var str="1.aaa 2.bbb 3.ccc"; str = '"' + str.replace(/(\\d+\\.)([az]+)/g, '$2').split(' ').join('","') + '"' console.log(str) 

I would do something like this: (Updated for second example)

 var s = "1.aaa 2.bbb 3.ccc"; var r = /\\d+\\.([^\\d]*)/g; var s2 = "1.aaa[2017-01-01] 2.bbb 3.ccc" var s3 = "1.aaa[2017-01-01] 2.bbb[2017-01-01] 3.ccc" var s4 = "1.aaa[2017-01-01] 2.bbb 3.ccc[2017-01-01]" var r2 = /\\d+\\.(.*?)( |$)/g function getGroups(s,r){ var matches = []; var m = r.exec(s); while (m != null){ matches.push(m[1]); m=r.exec(s); } return matches; } console.log(getGroups(s,r)); // ['aaa','bbb','ccc'] console.log(getGroups(s2,r2)); // [ 'aaa[2017-01-01]', 'bbb', 'ccc' ] console.log(getGroups(s3,r2)); // [ 'aaa[2017-01-01]', 'bbb[2017-01-01]', 'ccc' ] console.log(getGroups(s4,r2)); // [ 'aaa[2017-01-01]', 'bbb', 'ccc[2017-01-01]' ] 

See this question for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM