简体   繁体   中英

Regex: exclude string from matched pattern

Input string:

hrStorageDescr{hrStorageDescr="devfs: dev file system, mounted on: /.mount/dev"}

Regex to match value of hrStorageDescr only:

.*hrStorageDescr="(.*?)",.*

How to write this regex in order to preserve matching function, but exclude everything in the value, if devfs string is matched?

You could match bhrStorageDescr preceded by a word boundary \b

First match =" and assert what is directly to the right is not devfs followed by a word boundary using a negative lookahead (?!devfs\b)

If that assertion succeeds, capture in the group matching any char except a " using a negated character class and close the group before matching the closing double quote ([^"]+)

Using .* will match the last occurrence of the pattern, using .*? will match the first. If you want to match all occurrences you could omit that part, assuming you allowed to match all matches instead of a single match.

.*?\bhrStorageDescr="(?!devfs\b)([^"]+)"

Regex demo

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