使用正则表达式获取一些数据,但不是全部

问题描述 投票:0回答:1

我有一些这样的数据:

disconnected, received disassoc: sending station leaving (8)
disconnected, 4-way handshake timeout
disconnected, too weak signal, signal strength -91
disconnected, registered to other interface

我想得到没有数字和括号的原因。因此不要包含任何(x)-xx,其中x是数字(末尾)

输出应为

received disassoc: sending station leaving
4-way handshake timeout
too weak signal, signal strength
registered to other interface

我想我需要一些表情,但不确定。

这不起作用:

disconnected, (?<reason>.*)( -\d+)?

原因仍将包含-91

这仅给出带有-xx或(x)的行,其余行缺少

disconnected, (?<reason>.+(?=-\d+|\(\d\)))

这给出了所有行,但在原因中还将包括-xx和(x)

disconnected, (?<reason>.+(?=-\d+|\(\d\))?)

PS -xx(x)始终在末尾,因此可以使用锚点$

regex regex-lookarounds
1个回答
0
投票

您可以在可选的非捕获组中使用交替选项,以匹配字符串末尾的两个选项。

该值在命名捕获组reason中。

disconnected, (?<reason>.*?)(?:\(\d+\)| -\d+)?$

部分

  • [disconnected, 比赛已断开,并有空格
  • [(?<reason>.*?)命名捕获组reason,请尽可能匹配任何字符
  • (?:非捕获组
    • [\(\d+\)在括号之间匹配1+个数字
    • |
    • [ -\d+匹配空格-和1+个数字
  • [)?关闭组并使其为可选
  • [$字符串结尾

Regex demo

© www.soinside.com 2019 - 2024. All rights reserved.