使用节点中的正则表达式提取字符串

时间:2018-06-16 05:00:35

标签: node.js regex

我正在尝试将exec用于节点中的正则表达式。我知道该表达式通过在VSCode中使用扩展来测试它,但是当我运行节点应用程序时,它会一直返回null。

function toWeirdCase(s) {
  var str = s.split(''); // var str = {'h','e','l','l','o'}
  for (var i = 0; i < str.length; i++) {
    if (i % 2 !== 0) {                      //Test the index and not the letter
                                            //Since the goal is to capitalized the odd numbers (array starts at 0). You can use the condition i % 2 !== 0. This means the index reminder is not 0.
      str[i] = str[i].toUpperCase();        //Assign the value
    }
  }

  return str.join('');                      //Join the array and return
}

console.log(toWeirdCase('hello'))

3 个答案:

答案 0 :(得分:0)

您需要使用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');

希望有所帮助!

答案 1 :(得分:0)

您使用的正则表达式语法会显示出来。试试这样:

const regex = /^Program File:\s*(.*?)$/gm;
const str = `
Program Boot Directory: \\\\SIMPL\\\\app01
Source File:  C:\\\\DRI\\\\DRI\\\\DRI Conf Room v2 20180419aj
Program File: DRI Conf Room v2 20180419aj.smw
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

答案 2 :(得分:0)

我认为您不必在开始时转义\P,字符串以\r\n结尾,因此您可以匹配而不是\\匹配反斜杠。< / p>

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

例如:

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:(.*?)\r\n/;
var matched = regex.exec(str);
console.log(matched[0]);
console.log(matched[1]);

Demo