Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing "*" - Quantifier {x,y} following nothing

Tags:

c#

.net

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)%>
like image 325
loviji Avatar asked Nov 25 '09 16:11

loviji


3 Answers

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.

like image 50
Joey Avatar answered Nov 18 '22 21:11

Joey


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.

like image 22
Hans Kesting Avatar answered Nov 18 '22 23:11

Hans Kesting


thanks,

and I fixed like this

<%# Regex.Replace( (Model.Text ?? "").ToString(), Regex.Escape(patternText), "<b>" + patternText + "</b>", RegexOptions.IgnoreCase | RegexOptions.Multiline)%>
like image 2
loviji Avatar answered Nov 18 '22 23:11

loviji