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 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型