![](/img/trans.png)
[英]How do I geta string of text that lies between two '{'parenthesis'}' set using .NET?
[英]How do I extract a string of text that lies between *>…* using .NET C# regex or anything else?
我有這樣的字符串。
*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*
我想在*>
和*
字符之間提取。
我嘗試了這種模式,這在下面是錯誤的:
string pattern = "\\*\\>..\\*";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(seriGelen);
if (matches.Count > 0)
{
foreach (Match match in matches)
MessageBox.Show("{0}", match.Value);
}
字符串開頭是否有錯誤? 第一個數字后缺少星號? > -0.0532> -0.0534 *>
如果沒有,請嘗試此。
>([-+]?[0-9]*\.?[0-9]+)\*
C#代碼
string strRegex = @">([-+]?[0-9]*\.?[0-9]+)\*";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
string strTargetString = @">-0.0532>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
看起來可能會有非常不同的值(UPD:有一個整數正值)。 因此,讓我不要檢查數字格式。 我還將考慮*>
和>
, 以及 *
只是分隔符的不同變體。
我想提出以下解決方案。
(?<=[>\*])([^>\*]+?)(?=[>\*]+)
( http://regex101.com/r/mM7nK1 )
不確定是否理想。 僅當您的輸入以定界符開始和結束時才有效,但將允許您像代碼一樣使用匹配項而不是groups 。
========
但是您知道,為什么不使用String.Split
函數?
var toprint = seriGelen.Split(new [] {'>', '*'}, StringSplitOptions.RemoveEmptyEntries);
您可以使用簡單的正則表達式:
(?<=\*>).*?(?=\*)
樣例代碼:
string text = "*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0534*>-0.0534*>-0.0532*>-0.0532*>-0.0534*>-0.0534*>-0.0534*>-0.0532*>-0.0534*";
string[] values = Regex.Matches(text, @"(?<=\*>).*?(?=\*)")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.