简体   繁体   English

RegEx.Match未返回预期结果

[英]RegEx.Match not returning expected results

I am trying to build a regular expression that does matches only string2 below. 我正在尝试构建一个只匹配下面的string2的正则表达式。

string 1: (ABC12: CPBI, OTCBB:CPBI) 字符串1:(ABC12:CPBI,OTCBB:CPBI)

string 2: (ABC12: CPBI OTCF CPBI) 字符串2:(ABC12:CPBI OTCF CPBI)

Following is my C# code 以下是我的C#代码

private static Regex rxSymbol = new Regex(@"(?<=:)[&/\w -]+\s*(?=\))", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace ); 

rxSymbol.IsMatch(ticker) 

isMatch statement is returning true for string1. isMatch语句对string1返回true。 When I tried to get the exact match using rxSymbol.Match(ticker) , this is matching 'CPBI'. 当我尝试使用rxSymbol.Match(ticker)获得完全匹配时,这匹配'CPBI'。

I tested this Regex in RegexHero before using in my code. 我在使用我的代码之前在RegexHero中测试了这个正则表达式。 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*/ 我意识到问题是什么:只有当第一个:和第一个之间的文本匹配这个模式时,我希望正则表达式返回true:/ [&/ \\ w - ] + \\ s * /

In my example string (ABC12: CPBI, OTCBB:CPAA) there are two : and the regex is matching the text between 2nd : and ) 在我的示例字符串(ABC12:CPBI,OTCBB:CPAA)中有两个:正则表达式匹配第二个:和之间的文本

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+)+ . 我指定了第一部分(ABC12:\\(\\w+: .我也用更具体的部分替换了中间部分(\\s*\\w+)+

Note also that within square brackets [ ] , the special characters lose their meaning. 另请注意,在方括号[ ] ,特殊字符会失去意义。 Each character is taken as is. 每个角色都按原样拍摄。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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