正则表达式:将字符串与上一个匹配项进行匹配

时间:2019-03-23 12:35:02

标签: regex pcre grafana

我正在努力解决这个正则表达式难题,但这超出了我的专业知识...

我有这样的字符串:

字符串1:

$arr = [array]1
$arr.gettype().fullname
System.Object[]
([System.Object[]] | Get-Member -Static).where{$_.name -eq "ToString"}

$arr.toString()
System.Object[]

字符串2

Interface123|HostVienna ~ Tunnel22 ~ CustomerA ~ ServiceA  ~ Vienna, Street 10|HostAmsterdam ~ Interface123 ~ CustomerB ~ ServiceA  ~ Amsterdam, Street 40|HostSarajevo ~ Interface12 ~ CustomerC ~ ServiceA ~ Sarajevo, Street 1040

我正在尝试制作一个可以匹配从字符串开头到“ |”的所有内容的正则表达式(单词)并使用该匹配项,我试图找到以“ |”分隔的字符串包含那个词。在我的示例中,单词是Interface123|HostAmsterdam ~ Interface123 ~ CustomerB ~ ServiceA ~ Amsterdam,Street 40

从以上任一示例中,结果应为:

Interface123

使用纯正则表达式可能吗?

3 个答案:

答案 0 :(得分:1)

这可以通过regexp back引用实现,尽管并非每个实现都支持它们。像这样:

^([^|]+)\|(?:[^|]*\|)*?([^|]*\1[^|]*)

第二小组将捕获您的需求。

说明:^([^|]+)\|捕获您的关键字,(?:[^|]*\|)*?匹配零个或多个被'|'包围而没有关键字的字符串,([^|]*\1[^|]*)匹配您最终需要的内容。

Demo

答案 1 :(得分:1)

/^([^|]+)\|(?:[^|]+\|)*?\K[^|]*\b\1\b[^|]*/

在搜索下一个出现的位置时,重要的是要捕获它的针并最少使用字边界。

此外,将匹配作为字符串中的第一个,中间或最后一个数据集也很重要。这就是(?:[^|]+\|)*?

的重要性

演示:https://regex101.com/r/7lMwZf/5

故障:

^                     # start of string
([^|]+)\|             # capture needle then match first delimiting pipe
(?:[^|]+\|)*?         # match zero or more "sets of data"
\K[^|]*\b\1\b[^|]*    # forget previously matched characters with \K, then match set of data containing the needle until the end of string or first encountered pipe

答案 2 :(得分:0)

这是一个似乎有效的模式:

(?<=\||^)((?:(?!\|).)*Interface123.*?)(?=\||$)

这使用钢化的点来匹配所需的包含Interface123的字符串段。这是一个简短的解释:

(?<=\||^)       assert that what is prior is either pipe or the start of the string
((?:(?!\|).)*   consume anything so long is it is NOT pipe
Interface123.*? match 'Interface123` followed by anything up to
(?=\||$)        assert that what follows is either pipe or the end of the string

Demo

此答案使用环顾四周,但是根据您的评论,您的正则表达式风格与Perl兼容,这应该不是问题。

相关问题