Reputation: 1671
I have a String:
AAA foobarfoobarfoobar foo baar bar foo BBB and so on
After the Replace it should looke like:
AAA foobarfoobarfoobar foo baar bar foo
basically the BBB and everything behind it shall be stripped. so my first thought was an expression like:
BBB.*
Which actually does the Job. But i only want this to work, if BBB stands behind an AAA, so that
BBB bbb AAA aaa BBB ccc
whill be replaced to
BBB bbb AAA aaa
the first BBB is staying because there is no AAA in front of it.
my thought was an expression like
AAA.*?BBB.*
this would match the correct parts i think, but it will also kill the whole thing. So I know there are placeholders or something, but couldnt find out how to use them correctly. How is this done?
Upvotes: 0
Views: 264
Reputation: 354744
You can use a lookbehind:
(?<=AAA.*?)BBB.*$
which will ensure that AAA
will precede BBB
. Quick test:
PS> 'BBB bbb AAA aaa BBB ccc' -replace 'AAA.*?BBB.*$'
BBB bbb
PS> 'BBB bbb AAA aaa BBB ccc' -replace '(?<=AAA.*)BBB.*$'
BBB bbb AAA aaa
Upvotes: 2
Reputation: 93026
Try someting like this
(?<=AAA.*?)BBB.*
(?<=AAA.*)
is a look behind assertion, .net is able to handle them without length restriction, so it should be working for you.
The other solution would be
(AAA.*?)BBB.*
and replace with the content from the capturing group 1
Upvotes: 1
Reputation: 3289
i don't know how far c# implements those features, but you can use either
positive look-behind to find a match and don't replace it http://www.regular-expressions.info/lookaround.html
or you can store the (AAA.*) part and insert it in the replacement
Upvotes: 0