简体   繁体   中英

replace a word that start with “A” ,contains one or more “B” and end with C

I want to write a regex to replace

AAA XXX BBB XXX CCC

with

AAACCC

XXX can be any characters and must have one or more BBB between AAA and BBB,how to do?

Example:

before: AAA hello world BBB hello CCC
after: AAACCC

before: AAA hello world hello CCC
after: AAA hello world hello CCC

before: AAA hello BBB world BBB hello CCC
after: AAACCC

In c#:

string text = Regex.Replace( inputString, @"AAA.+BBB.+CCC", "AAACCC" );

input:

AAA hello world BBB hello CCC 
AAA hello world hello CCC
AAA hello BBB world BBB hello CCC

output:

AAACCC 
AAA hello world hello CCC
AAACCC

The pattern to search:

AAA.+?BBB.+?CCC

Replacement string:

AAACCCC

The trick is in .+? which is a non-greedy closure so that it will stop at the next match, not the last one.

I'd use lookahead:

string text = Regex.Replace( input, @"AAA(?=.*BBB).+?CCC" );

Input string:

AAA hello world BBB hello CCC 
AAA hello world hello CCC
AAA hello BBB world BBB hello CCC
AAA hello BBB world BBB hello CCC AAA hello BBB world BBB hello CCC
AAABBBCCC

output:

AAACCC 
AAA hello world hello CCC
AAACCC
AAACCC AAACCC
AAACCC

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