2017-02-26 37 views
2

我构建了RiveScript的chatbot子集,并尝试使用正则表达式构建模式匹配解析器。哪三个正则表达式匹配以下三个示例?用替代方案和可选方案解析正则表达式

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中,[*]是可选的通配符,表示可以接受空白文本。

回答

2
  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?
+0

什么有关此方案'(+ |。 *)告诉我 说(。+)'。如果在'告诉我说'之前有字符,那么''之间必须有一个空格以防止字碰撞,例如, “爱丽丝告诉我说你好,并且”告诉我说你好“应该可以工作,但是”让我说你好“不会。 – MiP

+1

只要删除'(。*)告诉我说(。+)'和'Alicetold me to say hi'的空格就会匹配。 – user

相关问题