简体   繁体   中英

How to get string value in brackets with regex

I have already seen another page that asks the same question however the answer given on that page does not seem to work for me.

I have a text file that contains a lot of words in square brackets and I am trying to remove the brackets. I have opened the text file and converted it to a string using the StreamReader class.

When I try to display the strings,none show up.

Can anybody tell me what i'm doing wrong here? Heres the code:

List<string> words = new List<string>();
            StreamReader sr = new StreamReader(File.OpenRead(ofd.FileName));
            string wordlist = sr.ReadToEnd();
            textEntry.Text = wordlist;
            MatchCollection matches = Regex.Matches(wordlist, "[(.+?)]", RegexOptions.Singleline);
            foreach (Match match in matches)
            {
                string add = match.Groups[1].Value;
                words.Add(add);
            }

            foreach (string word in words)
            {
                MessageBox.Show(word);
            }

Any help is appreciated,thanks.

You have to escape the brackets, since they are preserved keywords in regular expressions. You see in the code below the \\ is escaped too, since \\ has a special meaning in C#, so escape the escape character:

Regex.Matches(wordlist, "\\[(.+?)\\]", RegexOptions.Singleline);

Or, using the verbatim operator:

Regex.Matches(wordlist, @"\[(.+?)\]", RegexOptions.Singleline);

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