Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在节点中使用正则表达式提取字符串_Node.js_Regex - Fatal编程技术网

Node.js 在节点中使用正则表达式提取字符串

Node.js 在节点中使用正则表达式提取字符串,node.js,regex,Node.js,Regex,我正在尝试对节点中的正则表达式使用exec。我知道这个表达式是通过在VSCode中使用扩展名测试来工作的,但是当我运行node应用程序时,它总是返回null` str = '\r\nProgram Boot Directory: \\SIMPL\\app01\r\nSource File: C:\\DRI\\DRI\\DRI Conf Room v2 20180419aj\r\nProgram File: DRI Conf Room v2 20180419aj.smw\r\n'; var r

我正在尝试对节点中的正则表达式使用exec。我知道这个表达式是通过在VSCode中使用扩展名测试来工作的,但是当我运行node应用程序时,它总是返回null`

str = '\r\nProgram Boot Directory: \\SIMPL\\app01\r\nSource File:  C:\\DRI\\DRI\\DRI Conf Room v2 20180419aj\r\nProgram File: DRI Conf Room v2 20180419aj.smw\r\n';

var regex = /\Program File:(.*?)\\/;
var matched = regex.exec(str);
console.log(matched);

您需要使用RegExp构造函数:

var str = '\r\nProgram \r\nProgram File: DRI 0180419aj.smw\r\n'
    .replace('[\\r,\\n]',''); // removes the new lines before we search

var pattern = 'Program File.+' // write your raw pattern
var re = new RegExp(pattern); // feed that into the RegExp constructor with flags if needed

var result = re.exec(str); // run your search
console.log(result)
我不太确定你们的模式应该做什么,所以我只在那个里放了一个,它匹配以程序文件开头的任何东西。如果您想要所有匹配项,而不仅仅是第一个,只需将其更改为

var re = new RegExp(pattern,'g');

希望有帮助

您使用的正则表达式语法看起来不合适。试着这样做:

const regex=/^程序文件:\s**?$/gm; 常量str=` 程序启动目录:\\\\siml\\\\app01 源文件:C:\\\\DRI\\\\DRI\\\\DRI配置室v2 20180419aj 程序文件:DRI Conf v2室20180419aj.smw `; 让m; 而m=regex.execstr!==空的{ //这是避免具有零宽度匹配的无限循环所必需的 如果m.index==regex.lastIndex{ regex.lastIndex++; } //可以通过'm`-变量访问结果。 m、 forEachmatch,groupIndex=>{ log`find match,group${groupIndex}:${match}`; };
} 我认为您不必在开头转义\p,字符串以\r\n结尾,这样您就可以匹配它,而不是匹配反斜杠的\\

如果不希望在第一个捕获组中使用前导空格,可以添加\s*以匹配零个或多个空格字符:/Program File:\s*?\r\n/

例如:

str='\r\n程序启动目录:\\siml\\app01\r\n源文件:C:\\DRI\\DRI\\DRI\\DRI Conf Room v2 20180419aj\r\n程序文件:DRI Conf Room v2 20180419aj.smw\r\n'; var regex=/程序文件:.*?\r\n/; var matched=regex.execstr; console.logmatched[0];
控制台。日志匹配[1];你到底想看什么:DRI Conf v2室20180419aj.smw?是的。str实际上比这个大得多。它是从制造商的产品中提取运行代码的名称。对不起,我没有得到最后的评论。这是不是意味着你的问题没有得到解决或者其他什么?