简体   繁体   中英

Regex.Split everything inside square brackets []

I'm really a n00b when it comes to regular expressions. I've been trying to Split a string wherever there's a [----anything inside-----] for example.

string s = "Hello Word my name_is [right now I'm hungry] Julian";
string[] words = Regex.Split( s, "------");

The outcome would be "Hello Word my name_is " and " Julian"

The regex you want to use is:

Regex.Split( s, "\\[.*?\\]" );

Square brackets are special characters (specifying a character group), so they have to be escaped with a backslash. Inside the square brackets, you want any sequence of characters EXCEPT a close square bracket. There are a couple of ways to handle that. One is to specify [^\\]]* (explicitly specifying "not a close square bracket"). The other, as I used in my answer, is to specify that the match is not greedy by affixing a question mark after it. This tells the regular expression processor not to greedily consume as many characters as it can, but to stop as soon as the next expression is matched.

@"\\[.*?\\]"将匹配文本的括号

另一种写法:

Regex.Split(str, @"\[[^]]*\]");

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.

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