JS RegExp捕获每个比赛的所有组和pos

时间:2019-03-05 02:26:59

标签: javascript regex

声明: 我是RegExp的新手,正在尝试学习JavaScript中的捕获组

  1. 我正在使用https://regex101.com/r/COYhIc/1进行测试
  2. 请参见附件https://regex101.com中每个匹配项的字符pos列的图像

目标:

  1. 我想在控制台(完成)
  2. 上打印所有匹配项和组
  3. 我要打印每个匹配项的字符位置[查看图像] (剩余)

enter image description here

JSFIDDLE: https://jsfiddle.net/bababalcksheep/p28fmdk4/68/

JavaScript:

function parseQuery(query) {
  var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
  if (isRE) {
    try {
      query = new RegExp(isRE[1], isRE[2]);
    } catch (e) {}
  }
  return query;
}
var str = $('#str').val();
var regex = parseQuery($('#reg').val());
//
var result;
var match_no = 0;
var output = '';
while ((result = regex.exec(str)) !== null) {
  match_no++;
  output += `\nMatch ${match_no}\n`;
  output += `Full Match, ${ result[0]} , Pos\n`;
  for (i = 1; i < result.length; i++) {
    output += `Group ${i}, ${ result[i]} , Pos\n`;
  }
}
console.log(output);

2 个答案:

答案 0 :(得分:1)

根据文档RegExp.exec,您可以使用index属性对其进行检索。因此,我将此行添加到您的代码段中以检索完全匹配的列位置:

`${result.index}-${result.index + result[0].length}`

对于子组,JS不会检索索引,因此可以使用indexOf实现解决方法:

const initialSubGroupIndex = str.indexOf(result[i], result.index);
`${initialSubGroupIndex}-${initialSubGroupIndex + result[i].length}`

答案 1 :(得分:1)

在输出字段中,使用indexlastIndexexec返回具有索引属性的对象。

output += `Full Match, ${ result[0]} , Pos ${result.index} - ${regex.lastIndex}\n `;

更新组:

我使用了一个小的逻辑来获取索引:

var m = new RegExp(result[i]);
output += `Group ${i}, ${ result[i]}, Pos ${$('#str').val().match(m).index} - ${regex.lastIndex} \n`;

function parseQuery(query) {
  var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
  if (isRE) {
    try {
      query = new RegExp(isRE[1], isRE[2]);
    } catch (e) {}
  }
  return query;
}
var str = $('#str').val();
var regex = parseQuery($('#reg').val());
//
var result;
var match_no = 0;
var output = '';
while ((result = regex.exec(str)) !== null) {
  match_no++;
  output += `\nMatch ${match_no}\n`;
  output += `Full Match, ${ result[0]} , Pos ${result.index} - ${regex.lastIndex}\n `;
  for (i = 1; i < result.length; i++) {
    var m = new RegExp(result[i]);
    output += `Group ${i}, ${ result[i]}, Pos ${$('#str').val().match(m).index} - ${regex.lastIndex} \n`;
  }
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="form-group">
    <label for="str">String:</label>
    <input type="text" class="form-control" id="str" value="source=100, delta=2, source=2121, delta=5">
  </div>
  <div class="form-group">
    <label for="regex">Regex:</label>
    <input type="text" class="form-control" id="reg" value="/(source=(\d+))/g">
  </div>
  <div id="result">

  </div>
</div>

FIDDLE