我需要匹配整个字符串并使用ruby捕获text
,when
和image
的值,字符串上包含以下任何一种情况的字符串:
@bot post text:a when:b image:c
@bot post text:a
@bot post when:b image:c text:a
@bot post when:b text:a
我已经编写了一个适用于第一种情况的正则表达式:
/(?:@bot) post text:(?<text>.*) when:(?<when>.*) image:(?<image>.*)/
如何更改它以使每个参数都是可选的并且可以按任何顺序提供?
您可以使用https://www.playframework.com/documentation/2.5.x/PlayConsole
中的当前正则表达式答案 0 :(得分:1)
▶ "@bot post text:a when:b image:c".scan(/(text|when|image):(\S+)/).to_h
#⇒ {
# "image" => "c",
# "text" => "a",
# "when" => "b"
# }
要匹配整个字符串然后捕获,只需匹配整个字符串然后捕获:
▶ matcher = /(?:@bot) post ((text|when|image):(.+?)(?:\z|\s+))+/
▶ scanner = /(text|when|image):(\S+)/
▶ "@bot post text:a when:b image:c"[matcher].scan(scanner).to_h
或者,在一场比赛中:
▶ "@bot post text:a when:b image:c".match(
▷ /(?:@bot) post ((text:(?<text>\S*)|when:(?<when>\S*)|image:(?<image>\S*))\s*)+/)
#⇒ #<MatchData "@bot post text:a when:b image:c" text:"a" when:"b" image:"c">