简体   繁体   English

正则表达式,用于将字符串与插值占位符匹配

[英]Regex for matching a string with interpolation placeholders

Suppose I have a string with interpolation placeholder variables: 假设我有一个带有插值占位符变量的字符串:

"The %s fox %s over the lazy %s" 

For use with the % operator (what is it called in this context BTW?) eg: 与%运算符配合使用(在此情况下,它叫BTW吗?),例如:

"The %s fox %s over the lazy %s" % ["quick", "jumps", "dog"]

How would I write a Regex expression that would match any string against this uninterpolated string 我将如何编写一个正则表达式来匹配此未插值字符串的任何字符串

"The %s fox %s over the lazy %s"
"The quick fox jumps over the lazy dog"
"The 1 fox 2 over the lazy #@$#"

The easiest is to transform the pattern into regexp, with placeholders changed to capture-anything groups. 最简单的方法是将模式转换为正则表达式,并将占位符更改为捕获任何组。

strings = [
  "The %s fox %s over the lazy %s",
  "The quick fox jumps over the lazy dog",
  "The quick and agile fox nimbly jumps over the lazy son of a bitch",
  "The quick fox defiantly crawls under the lazy dog"
]

pattern = "The %s fox %s over the lazy %s" 

pattern_re = /^#{Regexp.escape(pattern).gsub(/%s/, '(.*)')}$/
strings.map { |string| pattern_re.match(string) }
# => [
#      #<MatchData "The %s fox %s over the lazy %s" 1:"%s" 2:"%s" 3:"%s">,
#      #<MatchData "The quick fox jumps over the lazy dog" 1:"quick" 2:"jumps" 3:"dog">,
#      #<MatchData "The quick and agile fox nimbly jumps over the lazy son of a bitch" 1:"quick and agile" 2:"nimbly jumps" 3:"son of a bitch">,
#      nil
#    ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM