33

fails when I try Regex.Replace() method. how can i fix it?

Replace.Method (String, String, MatchEvaluator, RegexOptions)

I try code

<%# Regex.Replace( (Model.Text ?? "").ToString(), patternText, "<b>" + patternText + "</b>", RegexOptions.IgnoreCase | RegexOptions.Multiline)%>
loviji
  • 12,620
  • 17
  • 63
  • 94

3 Answers3

53

Did you try using only the string "*" as a regular expression? At least that's what causes your error here:

PS Home:\> "a" -match "*"
The '-match' operator failed: parsing "*" - Quantifier {x,y} following nothing..
At line:1 char:11
+ "a" -match  <<<< "*"

The character * is special in regular expressions as it allows the preceding token to appear zero or more times. But there actually has to be something preceding it.

If you want to match a literal asterisk, then use \* as regular expression. Otherwise you need to specify what may get repeated. For example the regex a* matches either nothing or arbitrary many as in a row.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • Just to add a comment here for anyone using `Where-Object {$_ -notmatch '*text*text*'}` will fail, instead use `'text.text'` – user4317867 Dec 11 '15 at 21:09
21

You appear to have a lone "*" in your regex. That is not correct. A "*" does not mean "anything" (like in a file spec), but "the previous can be repeated 0 or more times".

If you want "anything" you have to write ".*". The "." means "any single character", which will then be repeated.

Edit: The same would happen if you use other quantifiers by their own: "+", "?" or "{n,m}" (where n and m are numbers that specify lower and upper limit).

  • "*" is identical to "{0,}",
  • "+" is identical to "{1,}",
  • "?" is identical to "{0,1}"

which might explain the text or the error message you get.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
2

thanks,

and I fixed like this

<%# Regex.Replace( (Model.Text ?? "").ToString(), Regex.Escape(patternText), "<b>" + patternText + "</b>", RegexOptions.IgnoreCase | RegexOptions.Multiline)%>
loviji
  • 12,620
  • 17
  • 63
  • 94
  • `(Model.Text ?? "").ToString()` is actually equivalent to just `Model.Text ?? ""`, as `ToString()` on a string just returns that string. – Joren Nov 25 '09 at 17:22
  • 1
    Why do you even use Regex.Replace when String.Replace will do the job? – erikkallen Nov 25 '09 at 17:30