简体   繁体   English

C#中的正则表达式匹配模式

[英]Regex Match Pattern in c#

Hey I have the following strings as input: 嘿,我有以下字符串作为输入:

"abcol"  
"ab_col"  
"cold"  
"col_ab"  
"col.ab"  

I have the string col to search from. 我有要搜索的字符串col。 I'm using regex to match 我正在使用正则表达式进行匹配

Match matchResults = Regex.Match(input , "col", RegexOptions.IgnoreCase);

I want to match only the string that has this pattern [Any special character or nothing ] + col + [Any special character or nothing] 我只想匹配具有此模式的字符串[Any special character or nothing ] + col + [Any special character or nothing]

From the above inputs, I want to return only ab_col, col_ab , col.ab 从以上输入中,我只想返回ab_col, col_ab , col.ab

Any help is highly appreciated. 非常感谢您的帮助。
Thanks 谢谢

[Any special character] = [^A-Za-z0-9] [任何特殊字符] = [^ A-Za-z0-9]

You can use this regex: - 您可以使用此正则表达式:-

(?:^.*[^a-zA-Z0-9]|^)col(?:[^a-zA-Z0-9].*$|$)

Explanation : - 说明:-

(?:   // non-capturing
  ^   // match at start of the string
  .*[^a-zA-Z0-9]  // match anything followed by a non-alphanumeric before `col`
    |     // or
  ^       // match the start itself (means nothing before col)
)
  col  // match col
(?:   // non-capturing
  [^a-zA-Z0-9].*  // match a non-alphanumeric after `col` followed by anything
   $     // match end of string
   |     // or
   $     // just match the end itself (nothing after col)
)

@"(^|.*[\\W_])col([\\W_].*|$)" this is your pattern. @"(^|.*[\\W_])col([\\W_].*|$)"这是您的模式。 \\w is alphanumeric character and \\W is non alphanumeric character. \\w是字母数字字符,而\\W是非字母数字字符。 ^ means line start and $ means line end. ^表示行开始, $表示行结束。 | is the or. 是或。 so (^|.*\\W) means line start or some characters and non alphanumeric after them. 因此(^|.*\\W)表示行首或后面的某些字符和非字母数字。

EDIT: 编辑:

yes, underline is alphanumeric too... so you should write [\\W_] (non alphanumeric or underline) instead of \\W 是的,下划线也是字母数字...所以您应该写[\\W_] (非字母数字或下划线)而不是\\W

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

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