使用替代项和可选项解析正则表达式

Parsing regex with alternatives and optionals

我正在构建 RiveScript 的聊天机器人子集,并尝试使用正则表达式构建模式匹配解析器。哪三个正则表达式匹配以下三个示例?

ex1: I am * years old
valid match:
- "I am 24 years old"
invalid match:
- "I am years old"

ex2: what color is [my|your|his|her] (bright red|blue|green|lemon chiffon) *
valid matches:
- "what color is lemon chiffon car"
- "what color is my some random text till the end of string"

ex3: [*] told me to say *
valid matches:
- "Bob and Alice told me to say hallelujah"
- "told me to say by nobody"

通配符意味着任何非空的文本都是可以接受的。

在示例 2 中,[ ] 之间的任何内容都是可选的,( ) 之间的任何内容都是可选的,每个选项或备选方案由 |.

分隔

在示例 3 中,[*] 是一个可选的通配符,表示可以接受空白文本。

  1. https://regex101.com/r/CuZuMi/4

    I am (?:\d+) years old
    
  2. https://regex101.com/r/CuZuMi/2

    what color is.*(?:my|your|his|her).*(?:bright red|blue|green|lemon chiffon)?.*
    
  3. https://regex101.com/r/CuZuMi/3

    .*told me to say.*
    

我主要使用两种东西:

  1. (?:) 非捕获组,将事物组合在一起,就像数学中使用的括号一样。
  2. .* 匹配任意字符 0 次或多次。可以替换为 {1,3} 以匹配 1 到 3 次。

您可以将 * 换成 + 以匹配至少 1 个字符,而不是 0 个。 非捕获组之后的 ? 使该组可选。


这些是您开始的黄金之地:

  1. http://www.rexegg.com/regex-quickstart.html
  2. https://regexone.com/
  3. http://www.regular-expressions.info/quickstart.html
  4. Reference - What does this regex mean?