简体   繁体   English

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

[英]Regex for text between two characters

I'm trying to get some text between two strings in C# in regex expression. 我试图在正则表达式中的C#中的两个字符串之间获取一些文本。 The text is in variable ( tb1.product_name ) : Example Text | a:10,Colour:Green 文本位于变量( tb1.product_name )中: Example Text | a:10,Colour:Green Example Text | a:10,Colour:Green

  1. Get all text before | 之前获取所有文本| , in this case, Example Text ,在这种情况下, Example Text
  2. Get all text between : and , , in this case, 10 获取所有文字之间:,在这种情况下, 10

In two differents regex. 有两种不同的正则表达式。 I try with: 我尝试:

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

But this doesn't work. 但这是行不通的。

If it is not so necessary to use regex, you can do this simply by using string.Substring & string.IndexOf : 如果没有必要使用正则表达式,则只需使用string.Substringstring.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);

Edit 1: 编辑1:

I feel Regex might be an overkill for something as simple as this. 我觉得正则Regex对于这样简单的事情可能是一个过大的杀伤力。 Also if use what i suggested, you can add Trim() at the end to remove whitespaces , if any. 另外,如果使用我的建议,则可以在末尾添加Trim()来删除空格 (如果有)。 Like: 喜欢:

string strBeforeVerticalBar = str.Substring(0, str.IndexOf('|')).Trim();
string strInBetweenColonAndComma = str.Substring(str.IndexOf(':') + 1, str.IndexOf(',') - str.IndexOf(':') - 1).Trim();
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM