[英]RegEx searching whole words ending or beginning with special symbols
I am trying to do a search in a file which may include a # and have tried the following two RegEx statements, and neither work. 我正在尝试在可能包含#的文件中进行搜索,并尝试了以下两个RegEx语句,但均无效。 Can someone show me the correct RegEx that I can search for regular alphanumeric characters and also if the user includes a # or another special character?
有人可以给我显示正确的RegEx,以便我可以搜索常规的字母数字字符,以及用户是否包含#或其他特殊字符吗?
Using NLog, I can see that the string is correctly sent to the web service. 使用NLog,我可以看到该字符串已正确发送到Web服务。 And then I build the following RegEx (tried 2 different ways).
然后,我构建以下RegEx(尝试了2种不同的方式)。
\b(?:C#)\b
\b(?:C\#)\b
Here is a partial string from my file that you see contains the string I'm searching for: 这是我文件中的部分字符串,您看到其中包含我要搜索的字符串:
by multiple customers C# both external and internal
C# Code: C#代码:
var reader = File.ReadAllText(currentFile);
var pattern = @"\b(?:" + searchPhrases[0] + @")\b"; \\ I've tried escaping it also.
// Works for a word like this ("White Paper" or "Paper" but not for "C# White Paper")
if (Regex.IsMatch(reader, pattern, RegexOptions.IgnoreCase))
{
searchResults.AppendLine(currentFile);
searchResults.Append("|");
}
Ajax: 阿贾克斯:
$.ajax({
url: "searchservice.asmx/SearchFiles",
data: { searchParameters: parameters, searchOnCompletePhrase: completePhrase },
type: "GET",
dataType: "text",
contentType: "text/plain; charset=utf-8",
success: function (data) {
processSearchData(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
lookupErrorDefinition(this);
console.log(XMLHttpRequest.status);
}
});
You can use one of the two solutions: 您可以使用以下两种解决方案之一:
var pattern = @"(?<!\w)(?:" + Regex.Escape(searchPhrases[0]) + @")(?!\w)";
Or 要么
var pattern = @"(?<!\S)(?:" + Regex.Escape(searchPhrases[0]) + @")(?!\S)";
In the first solution, (?<!\\w)
matches a location that is not preceded with a word char, and (?!\\w)
matches a location that is not followed with a word char. 在第一个解决方案中,
(?<!\\w)
匹配不带单词char的位置,而(?!\\w)
匹配不带单词char的位置。
In the second solution, (?<!\\S)
matches a location that is not preceded with a non-whitespace char (ie is preceded with whitespace or start of string), and (?!\\S)
matches a location that is not followed with a non-whitespace char (ie is followed with a whitespace char or end of string). 在第二个解决方案中,
(?<!\\S)
匹配不以非空白char开头的位置(即,以空白或字符串开头),而(?!\\S)
匹配不以非空白char开头的位置。后跟非空格字符(即,后跟空格字符或字符串结尾)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.