两个字符之间的文本的正则表达式

时间:2017-08-04 16:21:35

标签: c# regex

我正在尝试在regex表达式中的C#中的两个字符串之间获取一些文本。 文本位于变量(tb1.product_name)中:Example Text | a:10,Colour:Green

  1. |之前获取所有文字,在本例中为Example Text
  2. 获取:,之间的所有文字,在本例中为10
  3. 两个不同的正则表达式。 我试着用:

    Regex.Match(tb1.product_name, @"\:([^,]*)\)").Groups[1].Value

    但这不起作用。

2 个答案:

答案 0 :(得分:1)

如果不那么必要使用正则表达式,您只需使用string.Substring& string.IndexOf

string str = "Example Text | a:10,Colour:Green";
string strBeforeVerticalBar = str.Substring(0, str.IndexOf('|'));
string strInBetweenColonAndComma = str.Substring(str.IndexOf(':') + 1, str.IndexOf(',') - str.IndexOf(':') - 1);

修改1:

我觉得Regex对于像这样简单的事情可能有点过分。此外,如果使用我建议的内容,您可以在末尾添加Trim()以删除空格(如果有)。像:

string strBeforeVerticalBar = str.Substring(0, str.IndexOf('|')).Trim();
string strInBetweenColonAndComma = str.Substring(str.IndexOf(':') + 1, str.IndexOf(',') - str.IndexOf(':') - 1).Trim();

答案 1 :(得分:0)

string str = @"Example Text |a:10,Colour: Green";
Match match = Regex.Match(str, @"^([A-Za-z\s]*)|$");
Match match2= Regex.Match(str, @":([0-9]*),");
//output Example Text
Console.WriteLine(match.Groups[1].Value);
//output 10
Console.WriteLine(match2.Groups[1].Value);