[英]Regex: Get match from string into an object
我想用一個符合規則的字符串中的記錄填充一個對象。 規則是如果它包含至少3個點,右邊有一個空格( ". . . "
),那么我提取左邊的第一個文本,我剛剛選擇的文本及其長度。
string strdata = "Nume. . . . . . .Data nasterii. . . . .Nr. . . .";
Regex rgx = new Regex(". . . ");//At least 3 dots ". . . "
foreach (Match match in rgx.Matches(strdata))
lst.Add(new obj1{ Label = "?", Value = match.Groups[1].Value, Length = match.Groups[1].Length });
我想要實現:
問 :我必須使用哪種模式?
在正則表達式中, .
意味着匹配任何角色。 匹配一個.
,你需要將其作為\\.
來逃避\\.
。 要匹配表達式的2個或更多實例,請使用{2,}
。
string strdata = "Nume. . . . . . .Data nasterii. . . . .Nr. . . .";
Regex rgx = new Regex(@"(.+?)(\.( \.){2,})");//At least 3 dots ". . . "
foreach (Match match in rgx.Matches(strdata))
{
lst.Add(new obj1
{
Label = match.Groups[1].Value,
Value = match.Groups[2].Value,
Length = match.Groups[2].Length
});
}
您可以使用@"([\\w\\s]*)([\\. ]{3,})"
來實現我的假設。
正則表達式會將文本分成不同的組,在這些組中,您將獲得文本值和句點。
您可以通過輸入Nume. . . . . . .Data nasterii. . . . .Nr. . . .
使用此Regex Tester進行嘗試Nume. . . . . . .Data nasterii. . . . .Nr. . . .
Nume. . . . . . .Data nasterii. . . . .Nr. . . .
進入“源”字段,然后在([\\w\\s]*)([\\. ]{3,})
輸入“模式”字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.