I am trying to build a regular expression that does matches only string2 below.
string 1: (ABC12: CPBI, OTCBB:CPBI)
string 2: (ABC12: CPBI OTCF CPBI)
Following is my C# code
private static Regex rxSymbol = new Regex(@"(?<=:)[&/\w -]+\s*(?=\))", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace );
rxSymbol.IsMatch(ticker)
isMatch statement is returning true for string1. When I tried to get the exact match using rxSymbol.Match(ticker)
, this is matching 'CPBI'.
I tested this Regex in RegexHero before using in my code. It works correctly in regex Hero.
Can someone help me figure out what is wrong with my regular expression.
Update:
I realized what the problem is: I want the Regex to return true only if the text between the first : and the first ) matches this pattern: /[&/\\w -]+\\s*/
In my example string (ABC12: CPBI, OTCBB:CPAA) there are two :
and the regex is matching the text between 2nd : and )
How to modify this regex to enforce my requirement.
This seems to do the trick
(?<=\(\w+:)(\s*\w+)+(?=\))
I specified the first part (ABC12:
with \\(\\w+:
. I also replaced the middle part with the more specific one (\\s*\\w+)+
.
Note also that within square brackets [
]
, the special characters lose their meaning. Each character is taken as is.
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.