Regex Examples

From vWiki
Jump to navigation Jump to search

See the Regular Expressions page for more detail on syntax.

Useful/Standard RegEx

Matches Expression
IP Address ^\b((25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\b
Hostname (no domain) \A(\w|-)+
Email address \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
Multiple whitespace \b {2,}\b

Detailed Examples

Logfile Name

\d{4}-[A-Za-z]{3}-Week\d{1}.log

Example matches...

  • 2010-Feb-Week4.log
  • 2009-Dec-Week2.log
  • 1234-aBc-Week0.log

Between Parentheses

(?<=\[)(.*?)(?=\])

Matches everything between [ and ], so for example...

  • VMFS_SCSI_DS_01 is matched from [VMFS_SCSI_DS_01] My_VM/MyVM.vmdk

Its essentially done via three chunks of the regex...

  1. (?<=\[)
    • Requires that [ immediately proceeds the match
  2. (.*?)
    • Matches everything
  3. (?=\])
    • Requires that ] immediately follows the match

VMHBA LUN ID

(?<=:)([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$

Finds a number between 0 and 255 immediately after a : at the end of a line, specifically intended to get the LUN ID from a VMware canonical path, so for example...

  • 13 is matched from vmhba3:0:13

Stepping through the regex...

  1. (?<=:)
    • Requires that  : immediately proceeds the match
  2. ([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])
    • Matches any number between 0 and 255
  3. $
    • Ensures that the proceeding match occurs at the end of a line

vRanger Backup text in VM Notes

\s?\bvRanger.*Repository \[.*\]\s?

Finds the text created by vRanger in a VM's notes (so you can strip it out)...

  • EG vRanger Pro Backup: Type [Full] Result [Success] Time [27/09/2010 06:46:54] Repository [VC_Server]

Stepping through the regex...

  1. \s?
    • Matches any white-space at the start of the match
  2. \bvRanger.*
    • Matches vRanger at the start of a word and anything after until...
  3. Repository \[.*\]
    • Matches the end of a vRanger text segment, Repository [hostname]
  4. \s?
    • Matches any white-space at the end of the match

Script Version

(?<=v)[0-9]+(\.[0-9]+)+(?=.)

Gets the script version number off the end of a script name

  • EG Get 1.2.3 from Script-v1.2.3.ps1

Stepping through the regex...

  1. (?<=v)
    • Requires that v immediately precedes the match
  2. [0-9]+
    • Matches one or more digits
  3. (\.[0-9]+)+
    • Matches .n one or more times
  4. (?=.)
    • Requires that . follows the match

Lab Manager VM Prefix

(\b\d{6}-)

Matches the numeric prefix at the start of a Lab Manager VM name

  • EG Matches 002310- from 002310-Server-A-10