Reputation: 952
I've got quite a few regular expressions that I am using to capture info from a String. One example of a regular expression I am using is to capture a Word like "1ALPHA" :
string numUpperCaseStr = "[0-9][A-Z]+";
In case's like this when using these regular expressions what I'm curious about is what can I do in the regular expression to ensure I only capture the whole word with other regular expressions. For example I might have another regular expression like :
string allUpperStr = "[A-Z][A-Z]+";
if I use that regex I'll capture ALPHA from 1ALPHA and I don't want to. What can I do to limit these scenarios in regular expressions?
Upvotes: 1
Views: 80
Reputation: 335
Assuming that your words are space delimited, you could modify your regular expressions to only return items that both start and end with a space. The actual word can then extracted using a match group
(^|\s)([0-9][A-Z]+)(\s|$)
By placing parenthesis around the part of the word you want returned, you can then access that segment using match groups
Upvotes: 1
Reputation: 1989
You have to use word boundary:
string allUpperStr = "\b[A-Z][A-Z]+\b";
Upvotes: 1