PHP 回顾 javascript
PHP lookbehind in javascript
对于以下字符串,我想提取日期(星期一)、时间(6-8pm)和位置(Location1)
Date1: Monday, 6-8pm, Location1
Date2: Tuesday, 1-3pm, Location2
Date3: Wednesday, 4-6pm, Location3
在 PHP 中,我会 preg_match("/(?<=Date\d:\s)(.*),\s(.*),\s(.*)/", $input_line, $output_array);
使用 lookbehind 正则表达式,我可以使用 $output_array 在数组中单独显示数据,例如:
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
我只是想知道如何在 JavaScript 中实现同样的事情?
谢谢!
不确定如何使用 JS RegEx 一次进行多个匹配,但这里有一些非正则表达式的解决方案:
var input = "Date1: Monday, 6-8pm, Location1\n"
+ "Date2: Tuesday, 1-3pm, Location2\n"
+ "Date3: Wednesday, 4-6pm, Location3";
var input_lines = input.split("\n");
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);
}
或者,更短的版本:
var input = "Date1: Monday, 6-8pm, Location1\n"
+ "Date2: Tuesday, 1-3pm, Location2\n"
+ "Date3: Wednesday, 4-6pm, Location3";
output = [];
// Just a shortened version of the loop in the previous example.
input.split("\n").forEach(function(line){
output.push(line.replace(/Date[0-9]+:\s/, '').split(/,\s/));
});
对于以下字符串,我想提取日期(星期一)、时间(6-8pm)和位置(Location1)
Date1: Monday, 6-8pm, Location1
Date2: Tuesday, 1-3pm, Location2
Date3: Wednesday, 4-6pm, Location3
在 PHP 中,我会 preg_match("/(?<=Date\d:\s)(.*),\s(.*),\s(.*)/", $input_line, $output_array);
使用 lookbehind 正则表达式,我可以使用 $output_array 在数组中单独显示数据,例如:
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
我只是想知道如何在 JavaScript 中实现同样的事情?
谢谢!
不确定如何使用 JS RegEx 一次进行多个匹配,但这里有一些非正则表达式的解决方案:
var input = "Date1: Monday, 6-8pm, Location1\n"
+ "Date2: Tuesday, 1-3pm, Location2\n"
+ "Date3: Wednesday, 4-6pm, Location3";
var input_lines = input.split("\n");
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);
}
或者,更短的版本:
var input = "Date1: Monday, 6-8pm, Location1\n"
+ "Date2: Tuesday, 1-3pm, Location2\n"
+ "Date3: Wednesday, 4-6pm, Location3";
output = [];
// Just a shortened version of the loop in the previous example.
input.split("\n").forEach(function(line){
output.push(line.replace(/Date[0-9]+:\s/, '').split(/,\s/));
});