简体   繁体   中英

Finding and replacing using Regex

I am trying to find and replace a string when someone inputs it as a search query if they should misspell the code, for example Z0000ECEL is written as Z000ECEL it would replace it to be Z00+ECEL, this is so it finds the closest code to this and find it still even if they misspell it, I am currently using:

        if (Regex.IsMatch(searchWords[0], "^[a-z]+z00+", RegexOptions.IgnoreCase))
        {
            Regex.Replace(searchWords[0], "[0]+", "*0", RegexOptions.IgnoreCase);
        }

I do not want to place a wildcard at the start of the string as this will bring back to many results.

Is this doing what you want?

Regex.Replace(searchWords[0], "0{3,}", "00*");

this will replace 3 or more zeros with "00*"

You can also combine this with your first check

Regex.Replace(searchWords[0], "(?<=^[a-z]+z)0{3,}", "00*", RegexOptions.IgnoreCase);

This is involving a lookbehind assertion, so the 0{3,} will be only replaced, if there is a ^[az]+z before.

也许您正在寻找:

str = Regex.Replace(str, "(?i)(^[a-z]+0)0+", "$1+");

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