简体   繁体   中英

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. 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?

Using NLog, I can see that the string is correctly sent to the web service. And then I build the following RegEx (tried 2 different ways).

\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:

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM