简体   繁体   中英

Regular Expressions Replace with Placeholders

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?

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM