Eduards
Eduards

Reputation: 78

VBA python regular expression

I have a regular expression

^(.+?)M(\d+)(.+?)(?:\s.*)?$

Which splits occasions like "DIN934M12A2" but also occasions like "DIN934M12A2_LH" I need to define that regular expression so that occasions like "DIN934M12A2_LH" would not comply and return an error when I run such string in VBA.

As I'm really new to regular expressions, could someone, please, help me solve this problem?

Upvotes: 0

Views: 143

Answers (1)

The fourth bird
The fourth bird

Reputation: 163577

If you want 3 groups for the example data, you might make the pattern a bit more specific

^([^\W_]+)M(\d+)([^\W_]+)$

The pattern matches:

  • ^ Start of string
  • ([^\W_]+) Capture group 1, match 1+ word chars without an _
  • M Match literally
  • (\d+) Capture group 2, match 1+ digits
  • ([^\W_]+) Capture group 3, match 1+ word chars without an _
  • $ End of string

Regex demo

If you optionally want to match a whitespace char followed by optional chars:

^([^\W_]+)M(\d+)([^\W_]+)(?:\s.*)?$

Note that \s could also match a newline

Upvotes: 2

Related Questions