简体   繁体   中英

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 (ie 5th line) not the second occurrence (ie last line)?

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',)
>>>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM