C# 解析 "*" - 量词 {x,y}
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1798285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parsing "*" - Quantifier {x,y} following nothing
提问by loviji
fails when I try Regex.Replace()
method.
how can i fix it?
当我尝试Regex.Replace()
方法时失败。我该如何解决?
Replace.Method (String, String, MatchEvaluator, RegexOptions)
I try code
我试试代码
<%# Regex.Replace( (Model.Text ?? "").ToString(), patternText, "<b>" + patternText + "</b>", RegexOptions.IgnoreCase | RegexOptions.Multiline)%>
采纳答案by Joey
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 precedingtoken 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 whatmay get repeated. For example the regex a*
matches either nothing or arbitrary many a
s in a row.
如果要匹配文字星号,请\*
用作正则表达式。否则,你需要指定哪些可能会重复。例如,正则表达式在一行a*
中要么不匹配任何匹配,要么匹配任意多个a
。
回答by Hans Ke?ing
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".
您"*"
的正则表达式中似乎只有一个。那是不正确的。A"*"
并不意味着“任何东西”(就像在文件规范中一样),而是“前一个可以重复 0 次或更多次”。
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).
编辑:如果您自己使用其他量词,也会发生同样的情况:"+"
,"?"
或"{n,m}"
(其中 n 和 m 是指定下限和上限的数字)。
- "*" is identical to "{0,}",
- "+" is identical to "{1,}",
- "?" is identical to "{0,1}"
- “*”与“{0,}”相同,
- "+" 与 "{1,}" 相同,
- “?” 与“{0,1}”相同
which might explain the text or the error message you get.
这可能会解释您收到的文本或错误消息。
回答by loviji
thanks,
谢谢,
and I fixed like this
我是这样固定的
<%# Regex.Replace( (Model.Text ?? "").ToString(), Regex.Escape(patternText), "<b>" + patternText + "</b>", RegexOptions.IgnoreCase | RegexOptions.Multiline)%>