正则表达式:匹配单词或短语

Regular Expression: Match word or Phrase

本文关键字:短语 单词 正则表达式      更新时间:2023-09-26

目前,我在javascript中使用以下RegEx来匹配和计数字符串中的单词。与此ReEx:配合使用效果良好

RegEx:

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

关键词:美丽

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

输出:

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

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

关键词或短语:美丽的树

字符串:花园里美丽的树。花园里有一棵美丽的树。漂亮的模型树已经卖光了

输出:

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

我对RegExp不是很坚定。你有什么建议吗?感谢

怎么样

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

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

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 }