C
C#2w ago
yourFriend

Regex help.

For Learning purposes I want to match C# in given string. But the below pattern doesn't work for C# while it works for any alphabet word.
string s = "Just a random string in C#.";

string pattern = @"(?i:\bC#\b)";
Match match = Regex.Match(s, pattern);
// Doesn't work
// I also tried:
// @"(?i:\bC\#\b)" escaping #
// @"(?i:\bC\u0023\b)" using unicode

// But same pattern works for any other alphabetical word
string pattern2 = @"(?i:\brandom\b)";
Match match2 = Regex.Match(s, pattern2);
string s = "Just a random string in C#.";

string pattern = @"(?i:\bC#\b)";
Match match = Regex.Match(s, pattern);
// Doesn't work
// I also tried:
// @"(?i:\bC\#\b)" escaping #
// @"(?i:\bC\u0023\b)" using unicode

// But same pattern works for any other alphabetical word
string pattern2 = @"(?i:\brandom\b)";
Match match2 = Regex.Match(s, pattern2);
7 Replies
canton7
canton72w ago
.NET regexes don't use ?i IIRC? There are flags on Regex for that instead Ah no it does work, huh. It's unusual Ah, it's because "#" doesn't count as the end of a word
canton7
canton72w ago
"#" is in the "Other Punctuation (Po)" category (^|\W)(C#)(\W|$) or something might do it?
FusedQyou
FusedQyou2w ago
I don't know what you are trying to achieve given that this question is for fixing your regex, but if the whole point is to determine the location of "C#" in your string, then please just use IndexOf instead of overcomplicating it with a regex.
string s = "Just a random string in C#.";
int location = s.IndexOf("C#");
if (location != -1)
{
// Found.
}
string s = "Just a random string in C#.";
int location = s.IndexOf("C#");
if (location != -1)
{
// Found.
}
yourFriend
yourFriendOP2w ago
Thank you, I was wondering for hours lol. Ended up using (?i:\bC#\B). Just replaced the last \b with \B since # is not a word character.
canton7
canton72w ago
Hah, fair
yourFriend
yourFriendOP2w ago
Its for learning purposes only. Thank you for suggestion.

Did you find this page helpful?