【问题标题】:How to put an unmatched result in array using a Regexp?如何使用正则表达式将不匹配的结果放入数组中?
【发布时间】:2017-08-01 12:31:42
【问题描述】:

我想知道是否有可能从正则表达式中获取不匹配的结果并将这些值放入数组中(只是一个逆匹配)。

此代码使用替换部分处理解决方案:

str = 'Lorem ipsum dolor is amet <a id="2" css="sanitizer" href="#modal-collection"  data-toggle="modal" data-target="#ae" data-toggle="modal" data-attr-custom="test">Lorem ipsum </a> the end';

let elementRegexp: RegExp = new RegExp('<([^>]+?)([^>]*?)>(.*?)>','g');
let text = str.replace(elementRegexp, '');
let matchElements = str.match(elementRegexp);


console.log(text);

//Lorem ipsum dolor is amet  the end

console.log(text);
//["<a id="2" css="sanitizer" href="#modal-collection"…="modal" data-attr-custom="test">Lorem ipsum </a>"]

预期结果:

["Lorem ipsum dolor is amet", "end"]

jsFiddle

【问题讨论】:

  • 你可以.split()匹配的子字符串上的原始字符串。

标签: javascript arrays regex typescript regex-negation


【解决方案1】:

正如在 cmets 中提到的,您可以使用 split。这是工作代码:

"use strict";

let str = 'Lorem ipsum dolor is amet <a id="2" css="sanitizer" href="#modal-collection"  data-toggle="modal" data-target="#ae" data-toggle="modal" data-attr-custom="test">Lorem ipsum </a> the end';

let elementRegexp = new RegExp('<([^>]+?)([^>]*?)>(.*?)>','g');
let text = str.replace(elementRegexp, '');
let matchElements = str.match(elementRegexp);


console.log(text);

//Lorem ipsum dolor is amet  the end

console.log(matchElements);
//["<a id="2" css="sanitizer" href="#modal-collection"…="modal" data-attr-custom="test">Lorem ipsum </a>"]

console.log(str.split(matchElements));

当然,这在您有多个单独匹配项的更一般情况下不起作用。为此,您将需要一些更详细的内容。

那你可以试试这样的:

"use strict";

let str = 'Lorem ipsum <a>another</a> dolor is amet <a id="2" css="sanitizer" href="#modal-collection"  data-toggle="modal" data-target="#ae" data-toggle="modal" data-attr-custom="test">Lorem ipsum </a> the end';

let elementRegexp = new RegExp('<([^>]+?)([^>]*?)>(.*?)>','g');
let text = str.replace(elementRegexp, '');
let matchElements = str.match(elementRegexp);


console.log(text);
console.log(matchElements);

let newStr = str;
matchElements.forEach((match, idx) => {
  if (idx < matchElements.length - 1) {
    newStr = newStr.split(match).join('');
  } else {
    newStr = newStr.split(match);
  }
});
console.log(newStr);

【讨论】:

    猜你喜欢
    • 2016-11-10
    • 1970-01-01
    • 2011-10-26
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多