【问题标题】:Regex: first capital letter between punctuation and a word正则表达式:标点符号和单词之间的第一个大写字母
【发布时间】:2021-02-01 22:12:25
【问题描述】:

我正在尝试创建一个正则表达式来查找包含列表中某个单词的句子的开头。例如,如果我的字符串是:

“我在派。他去购物了!她上周四去了健身房。”

我的单词列表是 ["gym","Thursday"]

在字符串中搜索正则表达式应该返回“S”。

另一个例子:搜索字符串“明天是星期四。我要去健身房。”应该返回“T”(“明天”的第一个字母)。

最后,如果我有字符串“Thursday is tomorrow.”,我希望它在星期四返回“T”。

我现在拥有的是: (?<=[.?!\|])(?:(?![.?!\|]).)*?(gym|Thursday) 匹配“她去健身房”、“我要去健身房”等等。

【问题讨论】:

  • 尝试捕获它,/([A-Za-z])[^.?!|]*?\b(?:gym|Thursday)\b[^.?!|]*/

标签: javascript regex


【解决方案1】:

使用/(?:^|[.!] +)(?=[^.!]*\b(?:gym|Thursday)\b)(.)/:

const input = [
  'I at pie. He went shopping! She went to the gym last Thursday.',
  'Thursday is tomorrow.',
  'Tomorrow is Thursday. I will go to the gym.',
  'Tomorrow is Tuesday.'
];
const regex = /(?:^|[.!] +)(?=[^.!]*\b(?:gym|Thursday)\b)(.)/;
input.forEach((str) => {
  let m = str.match(regex);
  console.log(str + ' ==> ' + (m ? m[1] : null));
});

输出:

I at pie. He went shopping! She went to the gym last xThursday. ==> S
Thursday is tomorrow. ==> T
Tomorrow is Thursday. I will go to the gym. ==> T
Tomorrow is Tuesday. ==> null

解释:

  • (?:^|[.!] +) - 期望字符串的开头或句子的结尾(根据需要向字符类添加额外的字符)
  • (?=[^.!]*\b(?:gym|Thursday)\b) - gymThursday 的正向前瞻,位于句尾,由单词边界锚定
  • (.) - 捕获句子的第一个字符

【讨论】:

    【解决方案2】:
    /\b([A-Z])[^.?!\|]*?\b(gym|Thursday)/g
    

    Regex101

    这里唯一的技巧是使用[^.?!\|],它是“除句子终止符之外的任何字符”来匹配句子

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 2015-08-13
      相关资源
      最近更新 更多