RegEx用于匹配特定的日志模式

时间:2019-08-04 17:50:30

标签: regex regex-group regex-greedy

花了一些时间,但是正则表达式是一个词,很难弄清所有可能性,这是文本:

iPhone 5s (B6780382-ADBC-4F92-B1CA-52111A5A6FBE) (Shutdown)
iPhone 6 (FDA15891-2487-4C9E-A7F2-0E476C652E1D) (Shutdown)
iPhone 6 Plus (58D4FC86-8E22-4995-816D-BC8799AE1220) (Shutdown)
iPhone 6s (AE9BCF92-4814-4ABD-A791-FA60E0919156) (Shutdown)
iPhone 6s Plus (5D431BB6-42AE-455D-8501-2227687D1A00) (Shutdown)
iPhone 7 (0211256D-308F-4210-807D-DAAD02CC8AD9) (Shutdown)
iPhone 7 Plus (872D5513-434C-4618-9350-A2AB77B04459) (Shutdown)
iPhone 8 (74F7E423-1D17-475E-B18B-0FAAFC19DD0F) (Shutdown)
iPhone 8 Plus (DB424FB3-6D34-4FE9-82AD-E50F439A47AD) (Shutdown)
iPhone SE (ECF43B3D-38E1-4A37-8B07-C3CB72B14AE0) (Shutdown)
iPhone X (40D45896-6325-4BB6-99D2-420E3472B68E) (Shutdown)
iPhone Xs (5AAFEA8B-CE48-4DBE-9BAD-F9A714FAB4BA) (Shutdown)
iPhone Xs Max (29946005-C6FF-4E77-98C4-A104917A9FD9) (Shutdown)
iPhone Xʀ (205A5924-472E-4B83-AB7D-5FA56D93DC01) (Shutdown)
iPad Air (3rd generation) (54CE7050-9D80-4000-87AC-D1717C3F5890) (Shutdown)
iPad Air (83D98641-4FE8-476A-991E-14C0BF687DC6) (Shutdown)
iPad Air 2 (E6951B0F-2DD3-4361-8469-BA319D1FACA9) (Shutdown)
iPad (5th generation) (CB7A9551-9B29-4999-82A0-872C3700C316) (Shutdown)
iPad Pro (9.7-inch) (98FEC483-DC9B-4092-896E-CB9E8F165E51) (Shutdown)
iPad Pro (12.9-inch) (DD14F482-E456-4E6D-A044-C72818A7C52D) (Shutdown)
iPad Pro (12.9-inch) (2nd generation) (8C8364BA-A85D-4B3D-AD30-B179CA7F4541) (Shutdown)
iPad Pro (10.5-inch) (AA6DEE43-167D-42A4-9399-4727651BDAC7) (Shutdown)
iPad (6th generation) (040A1950-770F-4DB0-BC0A-91237C23AAC6) (Shutdown)
iPad Pro (11-inch) (07D97297-2E42-4FE8-B105-3245737D0CA3) (Shutdown)
iPad Pro (12.9-inch) (3rd generation) (692172E8-2AFB-465A-AC0D-4109AF1679B5) (Shutdown)

所以,对于我来说,已经确定的名称是可以的,例如“ iPhone”或“ iPad”,但这不仅是这个,这是我到目前为止所做的:

正则表达式:

((iPhone)|(iPad Air)|(iPad Pro)|(iPad))(\s)(\d{1}|\w{2}|\w{1}|\s)(\s)(\w{4}\s|\()

我需要按以下方式获取每行的每个项目:

iPad Pro (11-inch) (07D97297-2E42-4FE8-B105-3245737D0CA3) (Shutdown)

并且可以按组(例如名称)分组,在唯一键之后,最后状态为“关闭”

1 个答案:

答案 0 :(得分:3)

这是一种通用方法

(?im)^[^\S\r\n]*([^()\r\n]+?)[^\S\r\n]*(?:(\(.*?\)))?[^\S\r\n]*\(([a-f0-9]+(?:-[a-f0-9]+)*)\)[^\S\r\n]*(\(.*?\))

https://regex101.com/r/PZlZap/1

解释

 (?im)
 ^  
 [^\S\r\n]* 
 (                             # (1 start), Product
      [^()\r\n]+? 
 )                             # (1 end)
 [^\S\r\n]* 
 (?:
      (                             # (2 start), Optional Product description
           \( 
           .*? 
           \) 
      )                             # (2 end)
 )?
 [^\S\r\n]* 
 \( 
 (                             # (3 start), Product key
      [a-f0-9]+ 
      (?: - [a-f0-9]+ )*
 )                             # (3 end)
 \) 
 [^\S\r\n]* 
 (                             # (4 start), Shutdown
      \( 
      .*? 
      \) 
 )                             # (4 end)