Reputation: 1813
I've written a regex to match a short code in the format similar to:
[playername Le'Veon Bell]
Here is the regex:
\[playername\s+(?<name>[\w \-\'\’]+)\s*\]
I know the regex is struggling with the single quote in the player name. I've tested the regex here and it appears to work, but is not finding the match when I run the code from my web app.
Upvotes: 3
Views: 179
Reputation: 174786
For this example, you don't need to escape -
,'
symbols which are present inside the character class.
Regex rgx = new Regex(@"\[playername\s+(?<name>[\w '’-]+?)\s*\]");
Upvotes: 2
Reputation: 8212
Based on the information you provided I believe \[playername\s+(?<name>[^]]+?)\s*\]
should work.
The only real difference is in the capture group [^]]+
which matches any character that is NOT a ]
. This will effectively capture anything after [playername
up until the first ]
. It'll break if you have nested brackets.
Upvotes: 3
Reputation: 13286
Without knowing more about your scenario it's kind of difficult to say for sure, but from what you've got, I'd say you should switch to something more like this?
\[playername\s+(?<name>[^\]\s]*)\s+\]
That will match anything that doesn't have a square bracket or space in it, so it seems like what you're actually trying to do. I'd personally be tempted to remove the whitespace conditions, just on the grounds that a name might have a space in it. You could always call whatever your language's version of C#'s string.Trim()
is post-facto.
Note, of course, that it isn't exactly the same as what you're doing: you're limiting the characters explicitly. But it looks like you're trying to limit to any text anyway.
Upvotes: 0