简体   繁体   English

c#问题中的正则表达式

[英]Regex in c# question

been trying the to figure out the escape char for "["and "]" in regex. 一直试图找出正则表达式中“[”和“]”的转义字符。 I have the following pattern of string and this string is the actual string: 我有以下字符串模式,这个字符串是实际的字符串:

[somestring][anotherstring] [somestring] [anotherstring]

So the string will start with "[" followed by somestring and followed by with "]" and followed by "[" and followed by anotherstring and followed by "]". 所以字符串将以“[”后跟somestring开头,后跟“]”,然后是“[”,然后是anotherstring,后跟“]”。

can anyone please suggest? 任何人都可以建议吗?

@"(\[[^\]]+\]){2}"

I think (my head hurts a little now). 我想(我的脑袋现在疼了一点)。

Note, this will match anything between [ and ] . 注意,这将匹配[]之间的任何内容。

If it is only 1 level and you want to parse out the strings, then you do not need RegEx: 如果它只是1级并且您想要解析字符串,那么您不需要RegEx:

string composition = "[somestring][anotherstring]";
string[] stringSeparators = new string[] {"][", "[", "]"};
string[] s = composition.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

If you want to match for the exact pattern: 如果要匹配确切的模式:

Regex r = new Regex(@"^(\[[^\[\]]+\]){2}$");

Edit - to answer with syntax-highlighted code to the commenter: For parsing out the string Regex way using groups, you can use: 编辑 - 使用语法突出显示的代码回答评论者:要使用组解析字符串Regex方式,您可以使用:

foreach (Match match in Regex.Matches(composition, @"\[([^\[\]]+)\]"))
  Console.WriteLine(match.Groups[1].Value);

Escape the [ and ] with a '\\'. 用'\\'逃离[和]。

ie "\\[[A-Za-z]*\\]\\[[A-Za-z]*\\]" "\\[[A-Za-z]*\\]\\[[A-Za-z]*\\]"

http://gskinner.com/RegExr/ This site is awesome for playing around with regexes. http://gskinner.com/RegExr/这个网站很适合玩正则表达式。

Have Fun! 玩得开心!

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

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