none
why can not replace Business: to "" ? RRS feed

  • Question

  • why can not replace Business: to "" ?

    Regex rgx1 = new Regex("Business:* *Categories:* *");
                String r1 = rgx1.Replace("Business: Data Analysis", "").Trim();
    in VS2017, .net 4.5.2


    MEALY



    Thursday, August 17, 2017 4:41 PM

Answers

  • Because the Regex that you are passing does not match the string in the "Replace". Replace does not replace word by word. Instead, the whole Regex expression needs to be matched inside te string in order for the whole match to be replaced in bulk.

    By the way, the Regex that you wrote doesn't look right. It appears as if you think that the asterisk means "anhything here". Actually, it means "repeat the preceding character zero or more times".

    Thursday, August 17, 2017 8:43 PM
    Moderator

All replies

  • Because the Regex that you are passing does not match the string in the "Replace". Replace does not replace word by word. Instead, the whole Regex expression needs to be matched inside te string in order for the whole match to be replaced in bulk.

    By the way, the Regex that you wrote doesn't look right. It appears as if you think that the asterisk means "anhything here". Actually, it means "repeat the preceding character zero or more times".

    Thursday, August 17, 2017 8:43 PM
    Moderator
  • yes, i just want to replace 

    Business:    zero or more

    to empty string

    it seems match the pattern but can not match

    i change to 

    Regex rgx1 = new Regex("Business:* *Categories:* *[A-Za-z0-9]*");

    still can not match

    only this 

    Regex rgx1 = new Regex("Business:*");

    match,

    but previous version, i use Categories:*, this can be zero

    why

    Regex rgx1 = new Regex("Business:* *Categories:* *");

    not match?


    MEALY



    Thursday, August 17, 2017 9:02 PM
  • finally found () for word instead of character

    Regex rgx1 = new Regex("(Business:)* *(Categories:)* *");


    MEALY

    Thursday, August 17, 2017 11:11 PM