- Puppet 3 Cookbook
- John Arundel
- 411字
- 2021-04-09 23:52:28
Using regular expressions in if statements
Another kind of expression you can test in if
statements and other conditionals is the regular expression. A regular expression is a powerful way of comparing strings using pattern matching.
How to do it…
This is one example of using a regular expression in a conditional statement:
- Add the following to your manifest:
if $::lsbdistdescription =~ /LTS/ { notify { 'Looks like you are using a Long Term Support version of Ubuntu.': } } else { notify {'You might want to upgrade to a Long Term Support version of Ubuntu...': } }
How it works…
Puppet treats the text supplied between the forward slashes as a regular expression specifying the text to be matched. If the match succeeds, the if
expression will be true and so the code between the first set of curly braces will be executed.
If you wanted instead to do something if the text does not match, use !~
rather than =~
:
if $::lsbdistdescription !~ /LTS/ {
There's more…
Regular expressions are very powerful, but can be difficult to understand and debug. If you find yourself using a regular expression so complex that you can't see at a glance what it does, think about simplifying your design to make it easier. However, one particularly useful feature of regular expressions is the ability to capture patterns.
You can not only match text using a regular expression, but also capture the matched text and store it in a variable:
$input = 'Puppet is better than manual configuration' if $input =~ /(.*) is better than (.*)/ { notify { "You said '${0}'. Looks like you're comparing ${1} to ${2}!": } }
The preceding code produces this output:
You said 'Puppet is better than manual configuration'. Looks like you're comparing Puppet to manual configuration!
The variable $0
stores the whole matched text (assuming the overall match succeeded). If you put brackets around any part of the regular expression, that creates a group and any matched groups will also be stored in variables. The first matched group will be $1
, the second $2
, and so on, as in the preceding example.
Puppet's regular expression syntax is the same as Ruby's, so resources that explain Ruby regular expression syntax will also help you with Puppet. You can find a good introduction to Ruby regular expression syntax at this website:
http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm
See also
- Using regular expression substitutions, in this chapter
- ERP沙盤模擬教程
- 移動App測試的22條軍規(guī)
- 攝影照片修飾完全自學(xué)手冊
- Instant MuseScore
- Apache Solr 3.1 Cookbook
- 3dsMax 2018動畫制作基礎(chǔ)教程(第4版)
- 高等院校電腦美術(shù)教材:CorelDRAW X7中文版基礎(chǔ)教程
- After Effects 2022從新手到高手
- 無師自通AutoCAD 2014中文版機械設(shè)計
- 攝影師的后期必修課(調(diào)色篇)
- 零基礎(chǔ)攝影后期修圖 Photoshop照片處理輕松入門
- Quality Assurance for Dynamics AX-Based ERP Solutions
- Photoshop CC 2015中文版實用教程(第7版)
- Oracle 10g/11g Data and Database Management Utilities: LITE
- 中文版Photoshop CS6實用教程(第2版)