CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingEasy

A security analyst is writing a Python script to parse system logs. The script needs to extract specific error codes that follow a pattern like `ERROR-[A-Z]{3}-[0-9]{4}` from each line. Which Python module is best suited for this task?

  1. A`sys`
  2. B`re`
  3. C`os`
  4. D`json`
Show answer & explanation

Correct answer: B. `re`

The `re` module in Python provides regular expression operations. It is specifically designed for pattern matching, searching, and extracting information from strings using regular expressions, making it ideal for parsing log files for specific patterns like error codes.

Why the other options are wrong

  • A. The `sys` module provides access to system-specific parameters and functions, such as command-line arguments or Python interpreter details.
  • C. The `os` module provides a way of using operating system dependent functionality, such as interacting with the file system or environment variables.
  • D. The `json` module is used for encoding and decoding JSON data, not for general pattern matching in strings.

Python `re` Module

The `re` module in Python provides support for regular expressions (regex). It allows developers to define complex search patterns to match, find, and manipulate strings based on those patterns.

  • Used for pattern matching and string manipulation.
  • Common functions: `re.search()`, `re.findall()`, `re.match()`, `re.sub()`.
  • Patterns are defined using a specific regex syntax.

Memory trick: Regex needs 're', don't forget it, you see!

More Automation, Orchestration and Scripting questions