2015-04-06 53 views
-1

假设我有这样的如何替换重复范围内的所有字符串实例?

<other...Stuff> BoundsTag <relevant...Stuff> EndsBoundsTag <other...Stuff> BoundsTag <relevant...Stuff> EndsBoundsTag <other...Stuff> 

我想做一个搜索和我的字符串替换字符串,但如果其内BoundsTag/EndsBoundsTag只能改变它。我试图匹配的字符串在<relevant...Stuff><other...Stuff>中都存在很多次。此外,还有任意数量的BoundsTag/EndsBoundsTag对。

这可能与perl regexes?

这里就是我试图取代MyMatch

BoundsTag asdfasdfa MyMatch asdfasdfasdf MyMatch sdfasd EndsBoundsTag asdfasdfasdfsad **MyMatch** asd *MyMatch** asf2ef23fasdfasdf BoundsTag fghjfghj MyMatch fghjfghjgh MyMatch fghjfghj EndsBoundsTag 

在这里,我想更换MyMatch的所有实例除了**之间的那些特定字符串的例子。我不是特意指字符**,那些只是在那里指出来的。此外,间距只是易读性。

+0

发布一个示例以及预期输出。 – 2015-04-06 12:56:32

+1

这些对可以嵌套吗? – 2015-04-06 12:56:49

+0

@TimPietzcker好的问题,在我的情况下,不,他们不能 – 2015-04-06 13:00:08

回答

0

假设这些标签总是成对出现,并嵌套的,这很简单:

/Stuff(?=(?:(?!BoundsTag).)*EndsBoundsTag)/s 

将匹配Stuff只有EndsBoundsTag能后进行匹配,并在两者之间没有BoundsTag

在regex101.com上进行测试。

说明:

Stuff   # Match Stuff 
(?=    # only if the following matches afterwards: 
(?:   # 1. A group that matches... 
    (?!BoundsTag) # ...unless it's the start of "BoundsTag"... 
    .    # any character, 
)*    # repeated as needed. 
EndsBoundsTag # 2. EndsBoundsTag must also be present 
)    # End of lookahead - if that succeeds, we're between tags. 
+0

这似乎不工作?我修改了其他帖子的例子,看看我的意思 – 2015-04-06 13:09:01

+0

你是什么意思的“不起作用”,你是如何尝试呢? '$ subject =〜s/MyMatch(?=(?:(?!BoundsTag)。)* EndsBoundsTag)// sg;'应该从'$ subject'中删除所有'MyMatch'。 – 2015-04-06 13:45:46

+0

早些时候,当我尝试它只是没有匹配任何东西。现在,当我从您的评论中尝试您的示例时,它确实匹配。我怀疑我早些时候犯了一个愚蠢的错误,所以对我来说。我很抱歉。现在,它在第一个范围内匹配,但不在第二个范围内匹配... https://regex101.com/r/nH5uR7/4 – 2015-04-06 14:00:44

0

这是可能的。在Perl中,您可以使用此正则表达式:

\*{2}(?![^*]?\*{2})([^*]+?)\*{2} 

请参阅example here

+0

这只对每个标签有效。对于'BoundsTag Stuff Stuff EndsBoundsTag',只有第一个'Stuff'匹配。 – 2015-04-06 13:06:05

+0

是的@Tim Pietzcker https://regex101.com/r/nH5uR7/3 – 2015-04-06 13:08:14

+0

以上所有内容与当前OP示例输入和要求(关于标签内可能的重复内容没有任何关系)无关。 – 2015-04-06 13:11:48

相关问题