Answering to this question I stuck with this situation. Using reluctant match in my regex bring to this result
string s = Regex.Replace(".A.", "\\w*?", "B");
B.BAB.B
Why it doesn’t match and replace A?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because the
\\w*?matches as few\was it possibly can, including 0 of them.Since you have
\w*instead of\w+, the regex matches 0 or more\w.Since you have an additional
?on the\w*, the smallest possible match for this regex is the 0-length string, ”.Since the
?forces the regex to match as small a match as possible, it only ever matches 0-length strings. It can’t match a single characterAbecause that would be a longer match than the shortest.Hence all 0-length strings in
.A.(being:''.''A''.'', where each possible 0-length string is marked as'') are replaced with a ‘B’, giving you ‘B.A.B’.If you want to disable this behaviour and replace at least one
\w, you can use regex\w+?. However, by the same reasoning as before, the?forces this to only ever replace\wof length one, so you may as well use regex\w.