简体   繁体   中英

Regular Expressions to find and replace text

I have a string variable and following is the content of it:

.....
DataElement deAbtVersionNum
m_AttrParent commercialcardsys::CommercialCardInt
m_AttrGUIFieldLabel "WEX_CI 3.02.01P20.1" appsys30::lngDbb
m_AttrdbType "char"
.....

As the ... indicates, there maybe other text also.

In the third line we have "WEX_CI 3.02.01P20.1" (This is the only place starting from bottom where WEX.. is present.)

I need to replace 3.02.01P20.1(entirely) with a new version say 3.02.01P20.1.NEW

I have been able to do it using a dirty method which looks for the index of "Wex and then finds the next " and blah blah.

                int start = CItext.LastIndexOf("\"WEX") + 1;
                int end = CItext.IndexOf("\"", start);
                string text = CItext.Substring(start, end - start + 1);

                string[] parts = text.Split(new Char[] { ' ' });
                string editedText = parts[0] + " " + LabelName;
                CItext = CItext.Replace(text, editedText);

CIText is the string that I have to edit. LabelName is the string I want to put instead of 3.02.01P20.1

Can anyone suggest me any other clean method ?

I think you can use a regex with "lookahead". Try this.

var result = Regex.Replace(text, "(?<=WEX_CI )[^\"]+", "NEW", RegexOptions.Multiline);

试试这个正则表达式

var result =   Regex.Replace(text,@"(WEX_CI[\s][\da-zA-Z\.]+)","$1.NEW");

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