首页 > 解决方案 > 正则表达式从不同格式的字符串中查找数字

问题描述

我有以下文字:

instance=hostname1, topic="AB_CD_EF_12345_ZY_XW_001_000001"
instance=hostname2, topic="AB_CD_EF_1345_ZY_XW_001_00001"
instance=hostname1, topic="AB_CD_EF_1235_ZY_XW_001_000001"
instance=hostname2, topic="AB_CD_EF_GH_4567_ZY_XW_01_000001"
instance=hostname1, topic="AB_CD_EF_35678_ZY_XW_001_00001"
instance=hostname2, topic="AB_CD_EF_56789_ZY_XW_001_000001"

我想从上面的示例中捕获数字。我尝试使用下面的正则表达式来做到这一点,它们可以很好地作为单独的查询:

Regex: *.topic="AB_CD_EF_([^_]+).*    
Matches: 12345 1345 1235

Regex: *.topic="AB_CD_EF_GH_([^_]+).*
Matches: 4567 35678 56789

但我需要一个可以给我所有数字的正则表达式,即:

12345 1345 1235 4567 35678 56789

标签: regexregex-group

解决方案


设为GH_可选:

.*topic="AB_CD_EF_(GH_)?([^_]+).*

与您的所有目标号码匹配。

现场演示


通过允许使用任意数量的“字母下划线”序列,您可以更通用:

.*topic="(?:[A-Z]{2}_)+([^_]+).*

现场演示


推荐阅读