如何在Node.js中使用我的PHP正则expression式?

我在PHP中有一个正则expression式,但是当我把它移植到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);