代码之家  ›  专栏  ›  技术社区  ›  watchtower

用正则表达式捕捉撇号

  •  1
  • watchtower  · 技术社区  · 8 年前

    re 模块捕获单词的所有修饰语 color 在上午。英语(AmE)和Br。英语(BrE)。我成功地捕捉到了几乎所有的单词,除了以撇号结尾的单词。例如。 colors'

    以下是示例文本:

    Red is a color.
    His collar is too tight or too colouuuurful.
    These are bright colours.
    These are bright colors.
    Calorific is a scientific term.
    “Your life is very colorful,” she said.
    color (U.S. English, singular noun)
    colour (British English, singular noun)
    colors (U.S. English, plural noun)
    colours (British English, plural noun)
    color’s (U.S. English, possessive singular)
    colour’s (British English, possessive singular)
    colors’ (U.S. English, possessive plural)
    colours’ (British English, possessive plural)
    

    这是我的正则表达式: \bcolou?r(?:[a-zA-Z’s]+)?\b

    说明:

    \b                 # Start at word boundary
    colou?r            #u is optional for AmE
        (?:            #non-capturing group
        [a-zA-Z’s]+    #color could be followed by modifier (e.g.ful, or apostrophe)
        )?             #End non-capturing group; these letters are optional
    \b                 # End at word boundary
    

    问题是 colors’ 和 colours’ 匹配到 s . 撇号被忽略。有人能解释一下我的代码有什么问题吗?我是这么研究的 Regex Apostrophe how to match? ' 和 " .

    Regex101

    提前谢谢。

    2 回复  |  直到 8 年前
        1
  •  2
  •   CertainPerformance    8 年前

    问题是 \b 是一个词的边界,与 ...lors’ ,之间的位置 ’ 下面的空格是 不 一个词的边界,因为 空格也不是单词字符。而不是

    \bcolou?r(?:[a-zA-Z’s]+)?(?=[ .,])
    

    https://regex101.com/r/lB49Nr/3

        2
  •  0
  •   digitake    8 年前

    问题是结局 \b

    \b匹配,不消耗任何字符,直接在a 与\w匹配的字符和与\w不匹配的字符

    ’ 不在 \w 尝试删除结尾: \bcolou?r(?:[a-zA-Z’s]+)?