簡體   English   中英

正則表達式用於兩個字符之間的文本

[英]Regex for text between two characters

我試圖在正則表達式中的C#中的兩個字符串之間獲取一些文本。 文本位於變量( tb1.product_name )中: Example Text | a:10,Colour:Green Example Text | a:10,Colour:Green

  1. 之前獲取所有文本| ,在這種情況下, Example Text
  2. 獲取所有文字之間:,在這種情況下, 10

有兩種不同的正則表達式。 我嘗試:

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

但這是行不通的。

如果沒有必要使用正則表達式,則只需使用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);

編輯1:

我覺得正則Regex對於這樣簡單的事情可能是一個過大的殺傷力。 另外,如果使用我的建議,則可以在末尾添加Trim()來刪除空格 (如果有)。 喜歡:

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