More Regular Expressions: Using Lookarounds to Parse Data

Hands-On Lab

 

Photo of Elle Krout

Elle Krout

Content Team Lead in Content

Length

01:00:00

Difficulty

Intermediate

While using regular expressions, lookarounds allow us to create zero-width boundaries where the boundaries are also regular expressions. This will enable us to ensure that our primary expression either begins or ends with the provided lookaround or does not begin or end with the provided lookaround. The expression in the lookaround is matched, but not captured, so the resulting match is only the non-lookaround text. This allows us to fine-tune our expressions and ensure we're only matching what we want.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

More Regular Expressions: Using Lookarounds to Parse Data

Introduction

While using regular expressions, lookarounds allow us to create zero-width boundaries where the boundaries are also regular expressions. This will enable us to ensure that our primary expression either begins or ends with the provided lookaround or does not begin or end with the provided lookaround. The expression in the lookaround is matched, but not captured, so the resulting match is only the non-lookaround text. This allows us to fine-tune our expressions and ensure we're only matching what we want.

Solution

Begin by logging in to the lab server using the credentials provided on the hands-on lab page:

ssh cloud_user@PUBLIC_IP_ADDRESS

Remove excess spacing from highstate file

Remove the additional spacing before each line in the highstate file.

sed -i 's/^s*//g' highstate

Using regular expressions to provide the desired data

Craft a regular expression that will result in only the __id__, __run_num__, and __sls__ lines from the highstate file.

grep -Pzo '(?<=-{10})n__id__:(?:n|.)+?(?=changes:)' highstate

Create sls-report.txt

Save the newly-generated list of information to sls-report.txt.

grep -Pzo '(?<=-{10})n__id__:(?:n|.)+?(?=changes:)' highstate > sls-report.txt

Conclusion

Congratulations — you've completed this hands-on lab!