【问题标题】:Regex to grab key-value including the empty space [closed]正则表达式来获取键值,包括空格[关闭]
【发布时间】:2013-01-12 16:13:09
【问题描述】:

我在获取正则表达式中的空格时遇到了问题。 谁能帮助我使用键值机制提供正确的正则表达式。请注意,键值位置可能会发生变化而不是固定的。

正则表达式

\s*([\w\d_]*)=(.*?)\s+

输入

spt=38271 deviceExternalId=SUKUK node 1 dst=99.111.185.141 app=HTTPS rt=Jan 23 2013 15:30:45 deviceFacility=Packet filter msg=Connection was reset by server destinationTranslatedPort=443 

我的结果

Match 1: spt=38271 
    Subgroups:
    1: spt
    2: 38271
Match 2: deviceExternalId=SUKUK 
    Subgroups:
    1: deviceExternalId
    2: SUKUK
Match 3:  dst=99.111.185.141 
    Subgroups:
    1: dst
    2: 99.111.185.141
Match 4: app=HTTPS 
    Subgroups:
    1: app
    2: HTTPS
Match 5: rt=Jan 
    Subgroups:
    1: rt
    2: Jan          **==>Should grab [Jan 23 2013 15:30:45]**
Match 6:  deviceFacility=Packet 
    Subgroups:
    1: deviceFacility
    2: Packet       **==>Should grab [Packet filter]**
Match 7:  msg=Connection 
    Subgroups:
    1: msg
    2: Connection   **==>Should grab [Connection was reset by server]**
Match 8:  destinationTranslatedPort=443 
    Subgroups:
    1: destinationTranslatedPort
    2: 443

【问题讨论】:

  • 你不能为键值对设置单独的分隔符吗?根据您当前的文本,正则表达式无法获得所需的结果。试想一下,你会在什么基础上选择Packet filter 组合,但同时拒绝SUKUK node 被选中?

标签: java php regex perl expression


【解决方案1】:

试试这个:

([\w\d_]+)=(.*?)(?=\s+[\w\d_]+=|$)

print "$1\n$2";

【讨论】:

  • 它还会选择 OP 不想要的 SUKUK node 1
  • 我喜欢这个解决方案...但我必须做额外的拆分程序...但是非常好的主意...我喜欢它。
【解决方案2】:

更简单:\s*([\w\d_]*)=([^=]+)\s+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    相关资源
    最近更新 更多