簡體   English   中英

正則表達式捕獲部分行

[英]Regex Capture Parts of Line

我一直在努力捕獲 snmp 響應的一部分。

文本

IF-MIB::ifDescr.1 = 1/1/g1, Office to DMZ

正則表達式

(?P<ifDescr>(?<=ifDescr.\d = ).*)

當前捕獲

1/1/g1, Office to DMZ

如何只捕獲?

1/1/g1

Office to DMZ

編輯

1/1/g1

這應該與 snmp 響應中端口表示法的數字和正斜杠相匹配。

(?P<ifDescr>(?<=ifDescr.\d = )\d\/\d\/g\d)

鏈接到正則表達式

Office to DMZ

這應該通過端口符號開始匹配並捕獲剩余的描述。

(?P<ifDescr>(?<=ifDescr.\d = \d\/\d\/g\d, ).*)

鏈接到正則表達式

使用您顯示的示例,您能否嘗試使用具有可用 PCRE 選項的正則表達式。

(?<=IF-MIB::ifDescr)\.\d+\s=\s\K(?:\d+\/){2}g(?:\d+)

這是上述正則表達式的在線演示

或有一點變化使用以下內容:

(?<=IF-MIB::ifDescr)\.\d+\s=\s\K(?:(?:\d+\/){2}g\d+)

說明:為上文添加詳細說明。

(?<=IF-MIB::ifDescr)  ##using look behind to make sure all mentioned further conditions must be preceded by this expression(IF-MIB::ifDescr)
\.\d+\s=\s            ##Matching literal dot with digits one or more occurrences then with 1 or more occurrences of space = followed by one or more occurrences of spaces.
\K                    ##\K is GNU specific to simply forget(kind of) as of now matched regex and consider values in regex for further given expressions only.
(?:\d+\/){2}g(?:\d+)  ##Creating a non-capturing group where matching 1 or more digits with g and 1 or more digits.

沒有 PCRE 風格:要在第一個捕獲組中獲取值,請嘗試以下操作,OP 在對其工作的評論中確認了這一點。

(?<=IF-MIB::ifDescr)\.\d+\s=\s((\d+\/){2}g\d+)

您可以只使用我昨天給您的答案並將第一個返回組1/1/g10拆分為 '/' 並得到第三部分。

1/1/g10

用'/'分開給出

1
1
g10 <- third part

既然可以使用簡單的代碼來完成任務,為什么還要使用更復雜的正則表達式呢?

這是我的嘗試。

const string pattern = ".* = (.*), (.*)";
var r = Regex.Match(s, pattern);

const string pattern2 = ".* = ([0-9a-zA-Z\\/]*), (.*)";
var r2 = Regex.Match(s, pattern2);

使用命名捕獲組ifDescr捕獲值1/1/g1您可以使用匹配而不是環視。

(注意轉義點 \. 以字面匹配)

ifDescr\.\d+ = (?P<ifDescr>\d+\/\d+\/g\d+),

模式匹配:

  • ifDescr\.\d+ =匹配ifDescr. 和 1+ 數字后跟=
  • (?P<ifDescr>命名組ifDescr
    • \d+\/\d+\/g\d+匹配 1+ 位/ 1+ 位/g和 1+ 位
  • ),關閉組並匹配結尾的逗號

正則表達式演示

請執行下列操作:

ifDescr\.\d+\s=\s((?:\d\/){2}g\d+)

生成的捕獲組包含預期的結果。 請注意\d+接受一個或多個數字,因此您不需要您使用的 OR 運算符。

演示

或者,看起來g之后的數字將始終是ifDescr. . 如果是這種情況,請執行以下操作:

ifDescr\.(\d+)\s=\s((?:\d\/){2}g\1)

這基本上捕獲了一組中的數字,然后使用反向引用重用它來匹配(注意\1的用法)。 這種情況下的預期結果在第二個捕獲組中可用。

演示

我想這就是你要找的

= (.+), (.+)

它查找“=”,然后捕獲所有內容直到一個逗號,然后是所有內容。 它返回

1/1/g1
Office to DMZ

按照要求。

看到它在regex101.com上工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM