gpt4 book ai didi

javascript - 正则表达式: Match word or Phrase

转载 作者:行者123 更新时间:2023-12-03 11:46:19 25 4
gpt4 key购买 nike

目前,我在 JavaScript 中使用以下正则表达式来匹配和计算字符串中的单词。与此 ReEx 完美配合:

正则表达式:

var pickRegExp = /[^\W\d]+[\u00C0-\u017Fa-zA-Z'](\w|[-'](?=\w))*/gi;

关键字:美丽

字符串:花园里美丽的树。花园里有一棵美丽的树。

输出:

  • :4
  • 美丽:2
  • 树:2
  • 花园
  • 在:2

现在,我想要(精确地)匹配短语。例如

关键字或短语:美丽的树

字符串:花园里美丽的树。花园里有一棵美丽的树。美丽的模型树已售罄。

输出:

  • :4
  • 美丽的树:2
  • 树:1
  • 美丽:1
  • 花园
  • 在:2

我对正则表达式并不是很坚定。你有什么建议给我吗?谢谢您

最佳答案

怎么样

/\b(Beautiful tree|..*?)\b/gi

即精确匹配和通用单词匹配正则表达式之间的逻辑或?

s = ("The beautiful tree in the garden. In the garden is " +
"the beautiful tree. The model tree beautiful is sold out.");
result = {}
s.match(/\b(Beautiful tree|..*?)\b/gi).forEach(function(x) {
result[x] = (result[x]|0) + 1;
});

给出

{ " ": 15,
". ": 2,
"In": 1,
"The": 2,
"beautiful": 1,
"beautiful tree": 2,
"garden": 2,
"in": 1,
"is": 2,
"model": 1,
"out": 1,
"sold": 1,
"the": 3,
"tree": 1 }

关于javascript - 正则表达式: Match word or Phrase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26031775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com