简体   繁体   English

正则表达式:从匹配的模式中排除字符串

[英]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的值:

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

How to write this regex in order to preserve matching function, but exclude everything in the value, if devfs string is matched?如果devfs字符串匹配,如何编写此正则表达式以保留匹配的 function,但排除值中的所有内容?

You could match bhrStorageDescr preceded by a word boundary \b您可以匹配bhrStorageDescr前面有一个单词边界\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)首先匹配="并断言直接在右边的不是devfs后跟使用负前瞻(?!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 ([^"]+)如果该断言成功,则使用否定字符 class 在匹配除"之外的任何字符的组中捕获并在匹配结束双引号([^"]+)之前关闭组

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正则表达式演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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