Beginners guide for Regular Expressions(regexp)
Top 10 basic regexp to know for Ansible beginners while using "replace" or "lineinfile" modules
1. Start with Special character.
(dot) .
It selects all the content, expect new lines. example
2. To avoid and just want to select the literal character of (Dot). then use literal MetaCharacter as below
(back slash) \
3. When we want to select the exact word, as it is case senstive.
ex: try with "case sentive" vs "Case Sensitive"
4. When there is a repetition of the same word, but we need to select the word or character that begins the line. Beginning of a string - "^"
ex: ^xploritec.com
5. When we want to filter more specific word that starts with and end with.
Use Anchors "^" - Beginning of String and "$" - End of String
The below example has xploritec.com in two places but we need a specific one that starts at beginning of a line.
ex: ^xploritec.com$
6. Select a specific word that has a boundary.
ex: "GODOFFIRE Prometheus" and "GODOFFIREPrometheus"
when we just filter the word Prometheus, it will select all the matching words with or without boundaries. using "\bPrometheus" filter matches that have a Boundary as shown below.
"\b"
\bPrometheus
7. Opposite to the above selection, the word that should not have a Boundary.
"\B"
\BPrometheus
ex: Let's assume we have a 10 digit phone number, but it has no standard format and now we want to filter all the match cases.
"\d" "{}-quantifier" "dot(.) - selects any"
\d{3}.\d{3}.\d{4}
9. when we want to filter the exact literal match of a standard format along with specific starting area codes.
ex: 55* 66* 56* 65* - we can write as [56][65] as starting two numbers.
we can use character set [ ]
^[56][56]0-\d{3}-\d{4}
10. At times we have to filter and replace a combo of a few characters or words which has both numbers, special characters, and letters(including upper and lower cases)
ex: replace all the websites, emails, servernames etc with company proxy server.
we can use groups"()" and quantifiers"[]" to acheive this.
[a-zA-Z0-9-.]+(@|.)[a-zA-Z]+\.(com|edu|org)
Comments
Post a Comment