微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 JavaScript 正则表达式拆分此文本?

如何解决如何使用 JavaScript 正则表达式拆分此文本?

我想拆分此文本。我正在尝试使用 JavaScript 正则表达式。

(1) 真的不是。 (2) 嗯。 (3) 看哪,王子 (4) 是他自然元素的关键,在他生命中的女人的摆布下畏缩不前。 (5) 看到我,也许你想和我的女儿们一起喷,教她们一些组合。 (6) 毫无疑问,您是最好的老师,陛下。 (7) 例如,是我女儿教我现代世界的语言。

我想将其解析为片段组。我正在寻找这些结果之一。

[
  [1,"Really not."],[2,"Uh huh."],[3,"Behold Prince"],]


[
  {id: 1,text: "Really not."},{id: 2,text: "Uh huh."},{id: 3,text: "Behold Prince"},]

我使用这种模式。

/\(([0-9])\){1,3}(.+?)\(/g

你能帮我吗?我应该使用什么模式来正确拆分文本?

先谢谢你!

解决方法

你可以在javascript中使用regex和string.matchAll函数来做你想做的事情

const str = `(1) Really not. (2) Uh huh. (3) Behold Prince (4) are key in his natural element,cowering at the mercy of the women in his life. (5) See me perhaps you'd like to spout with my daughters and teach them some combination. (6) No doubt you are the best teacher,your majesty. (7) It is my daughter's that teach me in the languages of the modern world,for instance.`;

let array = [...str.matchAll(/\(([0-9]+)\)\s*(.*?)\s*(?=$|\()/g)].map(a=>[+a[1],a[2]])

console.log(array)

我使用 The fourth bird's regex 更新了我的答案,因为它比我写的正则表达式要干净得多。

,

您可以断言它或字符串的结尾,而不是匹配 (

这部分 \){1,3} 表示重复右括号 1-3 次。

如果要匹配 1-3 位数字:

\(([0-9]+)\)\s*(.*?)\s*(?=$|\()
  • \( 匹配 (
  • ([0-9]+) 捕获组1中的1+个数字(在代码中用m[1]表示)
  • \) 匹配 )
  • \s* 匹配可选的空白字符
  • (.*?)group 2 中捕获尽可能少的字符 (在代码中用 m[2] 表示)
  • \s* 匹配可选的空白字符
  • (?=$|\() 断言字符串的结尾或右侧的 (

Regex demo

const regex = /\(([0-9]+)\)\s*(.*?)\s*(?=$|\()/g;
const str = `(1) Really not. (2) Uh huh. (3) Behold Prince (4) are key in his natural element,for instance.`;
console.log(Array.from(str.matchAll(regex),m => [m[1],m[2]]));

,

... 一种基于 matchAll 以及 RegExp 的方法,它使用 named capture groupspositive lookahead ... /\((?<id>\d+)\)\s*(?<text>.*?)\s*(?=$|\()/g ...

// see ... [https://regex101.com/r/r39BoJ/1]
const regX = (/\((?<id>\d+)\)\s*(?<text>.*?)\s*(?=$|\()/g);

const text = "(1) Really not. (2) Uh huh. (3) Behold Prince (4) are key in his natural element,for instance."

console.log([
  ...text.matchAll(regX)
  ].map(
    ({groups: { id,text }}) => ({ id: Number(id),text })
  )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

注意

上述方法并未涵盖文本片段中开头括号/( 的出现(允许存在)。因此,为了始终处于保存状态,OP 应考虑基于 split / reduce 的方法......

const text = "  (1) Really not. (2) Uh (huh). (3) Behold Prince (4) are key in his natural element,(for instance).  "

console.log(
  text
    .split(/\s*\((\d+)\)\s*/)
    .slice(1)
    .reduce((list,item,idx) => {
      if (idx % 2 === 0) {
        list.push({ id: Number(item) });
      } else {
        // list.at(-1).text = item;
        list[list.length - 1].text = item.trim();
      }
      return list;
    },[])
);

// test / check ...
console.log(
  'text.split(/\s*\((\d+)\)\s*/) ...',text.split(/\s*\((\d+)\)\s*/)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。