如何提取与前面带句点(.)的同一字符串匹配的字符串?(仅使用正则表达式)

How to extract a string that matches with the same string with period(.) before it? (Only using Regular expressions)

本文关键字:字符串 串匹配 何提取 正则表达式 字符 前面 句点 提取      更新时间:2023-09-26

如果我有一个类似"this is a .period _test string"的字符串。如果我匹配"_test",那么它应该返回我"test",如果我匹配".period",它应该返回给我"period"

查找.period_test。然后使用子字符串移除._

  var regex = /(.period|_test)/gi; 
  var string = 'this is a .period _test string';
  var matches;
  while ((matches = regex.exec(str)) !== null) {
    if (matches.index === regex.lastIndex) {
       regex.lastIndex++;
   }
  console.log(matches[0].substring(1,matches[0].length));
  }