I would like to know if there is any way of checking if a string exists inside another string (ie contains function). I have been taken a look to http://forge.puppetlabs.com/puppetlabs/stdlib but I haven't found this specific function. Maybe this is possible through a regexp, but I am not really sure how to do it. Can anybody help me this one?
Asked
Active
Viewed 2.9k times
2 Answers
20
There is an "in" operator in Puppet:
# Right operand is a string:
'eat' in 'eaten' # resolves to true
'Eat' in 'eaten' # resolves to true
# Right operand is an array:
'eat' in ['eat', 'ate', 'eating'] # resolves to true
'Eat' in ['eat', 'ate', 'eating'] # resolves to true
# Right operand is a hash:
'eat' in { 'eat' => 'present tense', 'ate' => 'past tense'} # resolves to true
'eat' in { 'present' => 'eat', 'past' => 'ate' } # resolves to false
# Left operand is a regular expression (with the case-insensitive option "?i")
/(?i:EAT)/ in ['eat', 'ate', 'eating'] # resolves to true
# Left operand is a data type (matching integers between 100-199)
Integer[100, 199] in [1, 2, 125] # resolves to true
Integer[100, 199] in [1, 2, 25] # resolves to false
-
5@hveiga This should be the accepted answer, it's a much better answer to the question than the currently accepted answer (regex). – tonyg Jan 29 '16 at 14:00
-
2...but this answer would be better with examples inline. – larsks Jun 16 '18 at 16:37
-
Well THAT is lightly documented! I spent an hour looking for way to turn off regex string interpolation or a puppet function to escape regex characters so I could compare and match a string in a variable that contains a dot / period / special characters to another string that contains dots (in my case, subdomains). `$domain in $subdomain` - HOLY COW that's easier. Hopefully these keywords help this answer get picked up by search. – Bill McGonigle Apr 01 '21 at 22:18
14
This is quite easy to do, check out the docs here: http://docs.puppetlabs.com/puppet/2.7/reference/lang_conditional.html
A simple example:
if $hostname =~ /^www(\d+)\./ {
notice("Welcome to web server number $1")
}

Matt Cooper
- 9,962
- 2
- 31
- 26
-
1Link is broken, you can use https://puppet.com/docs/puppet/5.3/lang_expressions.html#regex-or-data-type-match instead. – Emmanuel Apr 16 '19 at 10:45