none
字符串"sdfsdf(1)",怎样使用正则获取该格式的字符串中括号内的内容和括号前面的字符串? RRS feed

  • 问题

  • 类似这样规范的字符串"afsdf(4)","345435(45)","asdas(445)",如何用用正则获取括号内的数字和"("左括号前面的字符串?括号内只能是数字字符,不然就匹配失败。获取的左括号前面的字符串不能是""空字符
    2017年5月10日 12:48

答案


  • Hi 便携式家园,

    >>类似这样规范的字符串"afsdf(4)","345435(45)","asdas(445)",如何用用正则获取括号内的数字和"("左括号前面的字符串?括号内只能是数字字符,不然就匹配失败。获取的左括号前面的字符串不能是""空字符

    根据你的描述,我写了下面的代码来实现。希望对你帮助。

        private void button_Click(object sender, RoutedEventArgs e)
            {
                List<string> liststrings = new List<string>() { "(263)", "afsdf(4AS)", "345435(45)", "asdas(445)" };
                foreach(string var in liststrings)
                {
                    string pattern = @"\(.*?\)";//匹配模式
                    Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
                    MatchCollection matches = regex.Matches(var);
                    string strq= var.Substring(0, var.LastIndexOf("("));
                    foreach (Match match in matches)
                    {
                        string value = match.Value.Trim('(', ')');
                        if (IsTextNumber(value)&& strq!="")
                        {
                            MessageBox.Show(strq + "  "+ value);
                        }
                    }
                }
            }
    
    
    
            private static bool IsTextNumber(string text)
            {
                Regex regex = new Regex("[^0-9.-]+");
                //regex that matches disallowed text
                return !regex.IsMatch(text);
            }
    

    Best Regards,

    Yohann Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2017年5月11日 7:37
    版主