【问题标题】:Get the value between the apostrophes in C#获取C#中撇号之间的值
【发布时间】:2012-06-16 14:57:17
【问题描述】:

我想提取撇号之间的值,例如从以下字符串中提取:package: name='com.app' versionCode='4' versionName='1.3' 这是开发 android 应用程序时“aapt”返回的内容。我必须得到值com.app41.3。我会很感激任何帮助:) 我找到了this,但这是 VBA。

【问题讨论】:

  • 我已经知道stirng.Split,但是我不想在撇号处拆分它,我想要它之间的值。
  • 使用撇号作为分割符,可以得到撇号之间的值。您的数组将是 {"name=", "com.app", " versionCode=", "4"...

标签: c# split apostrophe


【解决方案1】:

这个正则表达式应该适用于所有情况,假设' 字符仅作为值的封闭字符出现:

string input = "package: name='com.app' versionCode='4' versionName='1.3'";
string[] values = Regex.Matches(input, @"'(?<val>.*?)'")
                       .Cast<Match>()
                       .Select(match => match.Groups["val"].Value)
                       .ToArray();

【讨论】:

  • @P1nGu1n:我稍微修改了它以提高它的健壮性。请改用新版本。
  • 再次感谢您的解决方案!但是有什么区别呢?
  • 如果= 和开头的' 之间有任何空格,之前的版本会中断。例如,它不适用于name = 'value'
【解决方案2】:
string strRegex = @"(?<==\')(.*?)(?=\')";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"package: name='com.app' versionCode='4' versionName='1.3'";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // Add your code here
  }
}

RegEx Hero sample here.

【讨论】:

    【解决方案3】:

    如果您有兴趣,这里是您链接到的 VBA 的翻译:

    public static void Test1()
    {
        string sText = "this {is}  a {test}";
        Regex oRegExp = new Regex(@"{([^\}]+)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
        MatchCollection oMatches = oRegExp.Matches(sText);
        foreach (Match Text in oMatches)
        {
            Console.WriteLine(Text.Value.Substring(1));
        }
    }
    

    也在 VB.NET 中:

    Sub Test1()
        Dim sText = "this {is}  a {test}"
        Dim oRegExp = New Regex("{([^\}]+)", RegexOptions.IgnoreCase Or RegexOptions.CultureInvariant)
        Dim oMatches = oRegExp.Matches(sText)
        For Each Text As Match In oMatches
            Console.WriteLine(Mid(Text.Value, 2, Len(Text.Value)))
        Next
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2018-07-02
      • 2013-06-27
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多