简体   繁体   中英

Replace and remove a string via regex

This is first time I am working with regex.

The string below

var value ="abc ltd as yes"

need to be change to

var value ="abc Limited"

I have the following code:

  public static string Attempt_Prefix_Removal( string prefix, string replacement, bool remove = false)
    {

        if (remove == true)
        {

            var yesy = $"(?<!prefix )" + prefix + ".*";

            var test = Regex.Replace(prefix.ToLower(), $"(?<!prefix )" + prefix + ".*", replacement );



        }

        var output = (remove == true) ? Regex.Replace(prefix.ToLower(), $"(?<!prefix )" + prefix + ".*", replacement) :  Regex.Replace(prefix.ToLower(), $"(?<!prefix )" + prefix + "", replacement);

        return output;


    }

the values that are passed to the method are

prefix ="ltd", replacement = "Limited" , remove = ture

after running the code the result is

abc Limited as yes 

what do i need to change to get ride of as yes ?? thanks

private string regexOp(string sentence, string word, string wordtoReplace, bool isRemove)
    {
        var retValue = sentence;
        if (isRemove)
        {
            var Pattern = "^.*?(?=" + word + ")";
            Match result = Regex.Match(sentence, @Pattern);
            if (!string.IsNullOrEmpty(result.Value))
                retValue = result + wordtoReplace;
        }
        else
            retValue = Regex.Replace(sentence, word, wordtoReplace);

        return retValue;
    }

try this method, this will work as you expected with dynamic, do not forget to mark it as answer if this really helped you,

You may leverage this code:

var prefix ="ltd"; var replacement = "Limited";
var pat = $@"(?s)(?<!\w){Regex.Escape(prefix)}(?!\w){remove ? ".*" : string.Empty}";
return Regex.Replace(val, pat, replacement.Replace("$", "$$"));

See the C# demo online

The main points here are:

  • (?s) - will allow . match a newline (in case you will use .* in the pattern)
  • (?<!\\w){Regex.Escape(prefix)}(?!\\w) - the (?<!\\w) negative lookbehind will fail the match if the current location is preceded with a word char (you may further tweak the lookbehind pattern as per your requirements)
  • {remove ? ".*" : string.Empty} {remove ? ".*" : string.Empty} - this will either append .* (if remove is true ) or not.

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