正则表达式只返回第一个找到的

时间:2019-02-27 05:58:29

标签: regex

我正在尝试在字符串数据中搜索某个单词,但它只会返回第一个匹配项。

Option Explicit

Private Sub ComboBox1_Change()
    If ComboBox1.ListIndex > -1 Then Sheets(ComboBox1.Text).Select
End Sub

Private Sub Combobox1_DropbuttonClick()
    Dim xSheet As Worksheet
    On Error Resume Next
    Application.screenupdateing = False
    Application.EnableEvents = False
    If ComboBox1.ListCount <> ThisWorkbook.Sheets.Count Then
        ComboBox1.Clear
        For Each xSheet In ThisWorkbook.Sheets
            ComboBox1.AddItem xSheet.Name
            Next xSheet
    End If
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

Private Sub Combobx1_Gotfocus()
    If ComboBox1.ListCount <> 0 Then ComboBox1.DropDown
End Sub

我用另一种方式调用搜索功能:

const searchFunc = (stringData, searchedType) => {
  const regex = new RegExp(`${searchedType}(.*)`, "g");
  var arr = regex.exec(stringData);
  while (arr !== null) {
    prefix = arr[1].replace(/[`_:'",.]/gi, "")
    return prefix;
  }
};

我的strinData是这样的:

searchFunc(data, "path");

我得到的输出:

{
  path: '/aaa',
  ...
},
 {
  path: '/bbb',
  ...
  },
},  
{
  path: '/ccc',
  ...
},

我想要的输出

=>  /aaa

1 个答案:

答案 0 :(得分:1)

创建一个数组以放入结果,然后在push循环的每次迭代中将while放入该数组,并在函数末尾返回该数组:

const searchFunc = (stringData, searchedType) => {
  const pattern = new RegExp(`${searchedType}(.*)`, "g");
  const results = [];
  let match;
  while (match = pattern.exec(stringData)) {
    results.push(match[1].replace(/[`_:'",.]/gi, ""));
  }
  return results;
};
const data = `routes: [
{
  path: '/aaa',
  xxx: {
    ...
  },
},
 {
  path: '/bbb',
  xxx: {
    ...
  },
},
{
  path: '/ccc',
  xxx: {
    ...
  },
},
],`

const prefixValue = searchFunc(data, "path");
console.log(`prefix found => ${prefixValue}`);

请注意,这是一个X / Y问题:理想情况下,修复为该字符串提供服务的任何内容,以便为您提供正确的JSON,以便您可以将其解析为一个对象并使用对象/数组操作方法,例如:

const searchFunc = (data, prop) => data.map(obj => obj[prop]);
const dataArr = [{
    path: '/aaa',
    xxx: {},
  },
  {
    path: '/bbb',
    xxx: {},
  },
  {
    path: '/ccc',
    xxx: {},
  },
];

const prefixValue = searchFunc(dataArr, "path");
console.log(`prefix found => ${prefixValue}`);