Prime
Prime

Reputation: 3625

How to match only first occurrence using Regex

I have this custom log event which has Severity: HIGH repeated twice in every event. I tried to use regex to match only the first occurrence and remove/replace it. Before remove/replace the first match I tried to select the first match, but my regex matches the both occurrences.

Host: Hostname
VServer: NO
Version: Oracle v11
Cause: SQL exception
Severity: HIGH
JDKPath:  C:\Program Files\Java\jdk1.7.0\bin
Process: 2816
Severity: HIGH

This is my Regex which matches both the occurrences (Severity:)(.*) or (Severity:\s.*). How to match only first occurrence (i.e 5th line) not the second occurrence (i.e last line)?

Upvotes: 0

Views: 2408

Answers (2)

aneroid
aneroid

Reputation: 15961

In Python, re.search:

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

>>> import re
>>>
>>> log = """Host: Hostname
... VServer: NO
... Version: Oracle v11
... Cause: SQL exception
... Severity: HIGH
... JDKPath:  C:\Program Files\Java\jdk1.7.0\bin
... Process: 2816
... Severity: HIGH"""
>>>
>>> m = re.search('Severity\: (.*)', log)
>>> m.groups()
('HIGH',)

As you can see, only the first one matched.

Conversely, if you use re.findall or re.finditer, then you get both:

>>> b = re.findall('Severity\: (.*)', log)
>>> b
['HIGH', 'HIGH']
>>>
>>> for f in re.finditer('Severity\: (.*)', log):
...   print f.groups()
...
('HIGH',)
('HIGH',)
>>>

Upvotes: 1

BeetleJuice
BeetleJuice

Reputation: 40886

From your question, it's not clear in which context you're using Regex (you tagged PHP and Python) but in PHP, it's quite simple:

/(Severity:.*)/

demo

This works because by default, the .* token does not match a new line character. Since your Severity listings are on multiple lines, only the first line matches.

Upvotes: 1

Related Questions