0

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?

Jason Nichols
  • 3,739
  • 3
  • 29
  • 49
  • Could you edit your question to explain what you are doing a little better please... I don't understand your end goal... – Get Off My Lawn Sep 02 '17 at 02:37
  • Please edit your question to provide a minimal code sample that shows off your efforts and tell us what you want to achieve. Improve the grammar. – yacc Sep 02 '17 at 03:07

2 Answers2

0

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+\.)([a-z]+)/g, '$2').split(' ').join('","') + '"'

console.log(str)
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0

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.

Jason Nichols
  • 3,739
  • 3
  • 29
  • 49