我在PHP中有一个正则表达式,但是当我将其移植到Node.js时,我得到的输出与从PHP中得到的输出并不相同,但是我认为这是因为我真的不知道如何制作PREG_SET_ORDER在Node.js中工作。
示例文字:
INPUT - Each line represents a line inside a text file.
-------------------------------------------------------------------------------------
"!?Text" (1234) 1234-4321
"#1 Text" (1234) 1234-????
#2 Text (1234) {Some text (#1.1)} 1234
Text (1234) 1234
Some Other Text: More Text here 1234-4321 (1234) (V) 1234
PHP:
preg_match_all("/^((.*?) *\((\d+)\))(?: *\{((.*?) *\((.+?)\)) *\})?/m",$data,$r, PREG_SET_ORDER);
$i = 0;
foreach($r as $a) {
array_splice($a, 0, 2);
if(count($a) > 2) {
array_splice($a, 2, 1);
}
print_r($a);
}
Node.js:
var regex = /^((.*?) *\((\d+)\))(?: *\{((.*?) *\((.+?)\)) *\})?/mg
var result = data.toString().match(regex);
console.log(result);
PHP(输出):
Array
(
[0] => "!?Text"
[1] => 1234
)
Array
(
[0] => "#1 Text"
[1] => 1234
)
Array
(
[0] => #2 Text
[1] => 1234
[2] => Some text
[3] => #1.1
)
Array
(
[0] => Text
[1] => 1234
)
Array
(
[0] => Some Other Text: More Text here 1234-4321
[1] => 1234
)
Node.js(输出):
[ '"!?Text" (1234)',
'"#1 Text" (1234)',
'#2 Text (1234) {Some text (#1.1)}',
'Text (1234)',
'Some Other Text: More Text here 1234-4321 (1234)' ]
我设法使它像这样工作:
function data_to_array(data) {
var regex = '^((.*?) *\\((\\d+)\\))(?: *\\{((.*?) *\\((.+?)\\)) *\\})?';
var Regex = new RegExp(regex, 'mg');
var Matches = data.match(Regex);
matchesArray = new Array();
for (var i in Matches) {
ngRegex = new RegExp(regex);
ngMatches = Matches[i].match(ngRegex);
ngMatches.splice(0, 2);
if(ngMatches.length > 2) {
ngMatches.splice(2, 1);
}
matchesArray.push(ngMatches);
}
return matchesArray;
}
var output = data_to_array(data.toString());
console.log(output);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句