Split String using multiple Selectors

前端 未结 1 935
时光说笑
时光说笑 2021-01-25 07:39

I have below string :

var deptInfo = \"Flight-1 08:30~Flight-1 10:45|Flight-2 15:15~Flight-2 17:30\"

I want to have info in the format:

相关标签:
1条回答
  • You may use the following pattern to extract the necessary bits and then post-process the matches to get the necessary output:

    /(\d{2}:\d{2})~Flight-\d+\s*(\d{2}:\d{2})/g
    

    See the regex demo. Note you may even wrap the pattern with \b (word boundaries) if you want to make sure the first and last 2 digits are not preceded/followed with a word char, /\b(\d{2}:\d{2})~Flight-\d+\s*(\d{2}:\d{2})\b/g.

    Details

    • (\d{2}:\d{2}) - Group 1: 2 digits, :, 2 digits
    • ~Flight-\d+ - a ~Flight- substring and then 1+ digits
    • \s* - 0+ whitespaces
    • (\d{2}:\d{2}) - Group 2: 2 digits, :, 2 digits

    JS usage:

    var rx = /(\d{2}:\d{2})~Flight-\d+\s*(\d{2}:\d{2})/g;
    var s = "Flight-1 08:30~Flight-1 10:45|Flight-2 15:15~Flight-2 17:30";
    var m, res = [];
    while (m = rx.exec(s)) {
        res.push(m[1] + "-" + m[2]);
    } 
    console.log(res);

    0 讨论(0)
提交回复
热议问题