tags:

views:

381

answers:

3

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)%>
+2  A: 

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
+1  A: 

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
Any single character except, sometimes, newlines.
Joren
A: 

thanks,

and I fixed like this

<%# Regex.Replace( (Model.Text ?? "").ToString(), Regex.Escape(patternText), "<b>" + patternText + "</b>", RegexOptions.IgnoreCase | RegexOptions.Multiline)%>
loviji
`(Model.Text ?? "").ToString()` is actually equivalent to just `Model.Text ?? ""`, as `ToString()` on a string just returns that string.
Joren
Why do you even use Regex.Replace when String.Replace will do the job?
erikkallen