【问题标题】:Regex catch string between strings正则表达式捕获字符串之间的字符串
【发布时间】:2015-02-28 13:27:18
【问题描述】:

我创建了一个小函数来捕获字符串之间的字符串。

public static string[] _StringBetween(string sString, string sStart, string sEnd)
        {

            if (sStart == "" && sEnd == "")
            {
                return null;
            }
            string sPattern = sStart + "(.*?)" + sEnd;
            MatchCollection rgx  = Regex.Matches(sString, sPattern);
            if (rgx.Count < 1)
            {
                return null;
            }
            string[] matches = new string[rgx.Count];
            for (int i = 0; i < matches.Length; i++)
            {
                matches[i] = rgx[i].ToString();
                //MessageBox.Show(matches[i]);
            }

            return matches;
        }

但是,如果我这样调用我的函数:_StringBetween("[18][20][3][5][500][60]", "[", "]"); 它会失败。一种方法是如果我更改此行string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd; 但是我不能,因为我不知道字符是括号还是单词。

对不起,如果这是一个愚蠢的问题,但我找不到类似的搜索。

【问题讨论】:

  • 你到底想返回什么,一个字符串数组 "[18], [20], [3]..." 或者一个字符串数组 "18, 20, 3... “?该代码将返回第一个,但它的命名就好像您希望它返回后者一样。

标签: c# regex escaping


【解决方案1】:

如果我更改了此行字符串 sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd; 则可以是一种方法,但是我不能,因为我不知道该字符是括号还是单词。

你可以通过调用Regex.Escape来转义所有元字符:

string sPattern = Regex.Escape(sStart) + "(.*?)" + Regex.Escape(sEnd);

这将导致sStartsEnd 的内容按字面意思解释。

【讨论】:

  • 我也尝试了您之前发布的内容,但失败了,这就是我发布的原因!谢谢你:)
  • 是的,当然,它就像一个魅力。等待接受答案!
猜你喜欢
  • 1970-01-01
  • 2023-01-10
  • 2018-03-22
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
  • 1970-01-01
相关资源
最近更新 更多