douduiti3040 2016-08-06 23:21
浏览 25
已采纳

PHP在JavaScript中的lookbehind

For the following string, I would like to extract the date (Monday), time (6-8pm), and Location(Location1)

Date1: Monday, 6-8pm, Location1
Date2: Tuesday, 1-3pm, Location2
Date3: Wednesday, 4-6pm, Location3

In PHP, I would do preg_match("/(?<=Date\d:\s)(.*),\s(.*),\s(.*)/", $input_line, $output_array); using lookbehind regex, and I can use $output_array to display the data separtely in an array, like:

array[0][1] = Monday, array[0][2] = 6-8pm, array[0][3] = Location1 array[1][1] = Tuesday, array[1][2] = 1-3pm, array[1][3] = Location2 array[2][1] = Wednesday, array[2][2] = 4-6pm, array[2][3] = Location3

I was just wondering how could I achieve the same thing in JavaScript?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongqian8265 2016-08-07 00:38
    关注

    Not sure how to do multiple matches at once with JS RegEx, but here are some non-regex solutions:

    var input = "Date1: Monday, 6-8pm, Location1
    "
              + "Date2: Tuesday, 1-3pm, Location2
    "
              + "Date3: Wednesday, 4-6pm, Location3";
    
    var input_lines = input.split("
    ");
    
    var output = [];
    
    for(var iterator = 0;iterator < input_lines.length;iterator++){
        var input_line = input_lines[iterator];
    
        input_line = input_line.replace(/Date[0-9]+:\s/, '');
    
        var line_data = input_line.split(/,\s/);
    
        output.push(line_data);
    }
    

    Or, a shorter version:

    var input = "Date1: Monday, 6-8pm, Location1
    "
              + "Date2: Tuesday, 1-3pm, Location2
    "
              + "Date3: Wednesday, 4-6pm, Location3";
    
    output = [];
    
    // Just a shortened version of the loop in the previous example.
    input.split("
    ").forEach(function(line){
        output.push(line.replace(/Date[0-9]+:\s/, '').split(/,\s/));
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错