如何匹配/捕获关键字和下一个出现的空行(或字符串末尾)之间的多行子字符串?

问题描述 投票:0回答:1

我四处搜寻,找不到任何可以帮助我的东西。我希望得到一些帮助。

JavaScript 代码搜索文本正文并找到一个短语,然后它应该在找到它后抓取整个文本。

在单行字符串上效果很好,但在多行上效果不佳:(

理想情况下,我可以在同一个文本框中列出所有颜色,并用逗号分隔。

就像给我“颜色受影响”之后的所有内容,直到我们到达空行。 这可能吗?

https://jsfiddle.net/fenster89411/knrzpvta/3/工作示例

function extractInfo() {
  var text = document.getElementById('textarea').value
  text = text.split('\n')

  for (let i = 0; i < text.length; i += 1) {
    if (text[i].includes('Scheduled Maintenance')) {
      var approverName = text[i].replace('Scheduled', '').trim();
      document.getElementById('approvername').value = approverName;
    }
    if (text[i].includes('Maintenance ID')) {
      var approverEmail = text[i].replace(/.*Maintenance ID\D*(\d*).*/, '$1').trim();
      document.getElementById('approveremail').value = approverEmail;
    }
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Information Extraction</title>
</head>
<body>

<textarea id="textarea" rows="20" cols="50">
Scheduled Maintenance 44445555666 - Multiple COLOURS Affected
Maintenance ID 444555666 
Colours affected

Yellow
Blue
Black
red
purple
</textarea>

<button onclick="extractInfo()">Extract Information</button>

<!-- Display extracted information -->
<div>
  <label for="approvername">Scheduled Maintenance Name:</label>
  <input type="text" id="approvername" readonly>
</div>
<div>
  <label for="approveremail">Maintenance ID Email:</label>
  <input type="text" id="approveremail" readonly>
</div>


<script src="script.js"></script>

</body>
</html>

javascript regex string regex-group multiline
1个回答
0
投票

几乎涵盖任何可能的有效场景的正则表达式可能类似于以下内容......

const regXColors = /Colours\s+affected(?:\n+(?:(?:(.*?)(?:\n{2,}|\n$))|(.*)))/gs;

...并且其模式在其游乐场页面得到解释

为了提取预期结果,可以利用

RegExp.prototype.exec
及其 结果数组,其中可以访问模式的两个 捕获组 的值。部分利用OP的原始示例代码,可以实现如下所示的实现...

function getAllAffectedColors(value) {
  const regXColors =
    // see ... [https://regex101.com/r/dKw9gG/1]
    /Colours\s+affected(?:\n+(?:(?:(.*?)(?:\n{2,}|\n$))|(.*)))/gs;

  const regXResult = regXColors.exec(value) ?? [];
  const colorValue = (regXResult[1] || regXResult[2]) ?? null;

  return (colorValue === null) ? [] : colorValue.split(/\n/);
}
function logAllAffectedColors() {
  const textValue = document.querySelector('#textarea').value;
  const colorList = getAllAffectedColors(textValue);

  console.clear();
  console.log({ colorList, colorString: colorList.join(', ') });
}
document
  .querySelector('button')
  .addEventListener('click', logAllAffectedColors);
body { margin: 0; }
button { display: block; }
textarea { width: 40%; }
.as-console-wrapper { left: auto!important; width: 57%; min-height: 100%; }
<textarea id="textarea" rows="11" cols="30">
Maintenance ID 444555666 
Colours affected


Yellow
Blue
Black
red
purple

</textarea>

<button>log all affected colors</button>

© www.soinside.com 2019 - 2024. All rights reserved.