使用RegEx进行JavaScript拆分而不进行全局匹配

我有一个表情。

var expression = "Q101='You will have an answer here like a string for instance.'"

我有一个搜索表达式的正则表达式。

var regEx = new regExp(/=|<>|like/)

我想使用正则表达式拆分表达式。​​

var result = expression.split(regExp)

这将返回以下内容:

["Q101","'You will have an answer here "," a string for instance'"]

这不是我想要的。

我应该有:

["Q101","'You will have an answer here like a string for instance'"]

如何使用上面的正则表达式仅在第一匹配项上进行分割?

guibin948702526 回答:使用RegEx进行JavaScript拆分而不进行全局匹配

由于您只想抓住第一个定界符两侧的两个部分,因此使用String.match并丢弃整个匹配项可能会更容易:

var expression = "Q101='You will have an answer here like a string for instance.'";

var parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);

expression = "Q101like'This answer uses like twice'";
parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);

,

JavaScript的split方法无法完全满足您的要求,因为它会在所有匹配项上拆分,或者在N个匹配项后停止。您需要执行一个额外的步骤来找到第一个匹配项,然后使用自定义函数将第一个匹配项拆分一次:

function splitMatch(string,match) {
  var splitString = match[0];
  var result = [
    expression.slice(0,match.index),expression.slice(match.index + splitString.length)
  ];
  return result;
}

var expression = "Q101='You will have an answer here like a string for instance.'"

var regEx = new RegExp(/=|<>|like/)
var match = regEx.exec(expression)

if (match) {
  var result = splitMatch(expression,match);
  console.log(result);
}
,

尽管JavaScript的split方法does具有可选的limit参数,但它只是丢弃结果中太长的部分(与Python的split不同) 。要在JS中执行此操作,您需要考虑匹配的长度,手动将其拆分-

const exp = "Q101='You will have an answer here like a string for instance.'"

const splitRxp = /=|<>|like/
const splitPos = exp.search(splitRxp)
const splitStr = exp.match(splitRxp)[0]

const result = splitPos != -1 ? (
  [
    exp.substring(0,splitPos),exp.substring(splitPos + splitStr.length),]
) : (
  null
);

console.log(result)

本文链接:https://www.f2er.com/3098654.html

大家都在问