[英]Regex to select a pattern of SubString
在Regx C#中查找和選擇字符串的一部分的語法是什么?
該字符串可以是:
string tdInnerHtml = "<strong> You gained 230 Points </strong>
there is going to be more text and some html code part of this
string <a href=http://google.com>Google it here </a>";
// I want to extract 230 from this string using Regx.
// The digits (230) vary for each tdInnerHtml.
// So code would be to look for digits, followed by space, ending with Points
如果空格和</strong>
標簽一致,則可以使用以下命令在此處進行匹配,並且可以與類似的字符串一起使用:“ 品脫在230-240點之間,您獲得了230點 ”
var match = Regex.Match(tdInnerHtml, @"(?<pts>\d+) Points ?</strong>");
if (match.Success) {
int points = Convert.ToInt32(match.Groups["pts"].Value);
Console.WriteLine("Points: {0}", points);
}
只要您只輸入一組數字,然后輸入Points
,Regex就可以正常工作:
Match match = Regex.Match(tdInnerHtml, @"(?<![\d-])(\d+) Points");
if (match.Success){
// fetch result
String pointsString = match.Groups[1].Value;
// optional: parse to integer
Int32 points;
if (Int32.TryParse(pointsString, out points)){
// you now have an integer value
}
}
但是,如果這與信息在頁面上的位置有任何關系,請格式化其周圍的格式或其他與HTML相關的內容-請注意其他人的警告並使用HTML解析器。
正則表達式非常簡單, \\d+ Points
。 這里是C#,帶有命名的組捕獲:
var match = Regex.Match(tdInnerHtml, "(?<pts>\d+) Points");
if (match.Success) {
int points = (int)match.Groups["pts"].Value;
// do something..
}
string test = "<strong> You gained 230 Points </strong>";
string pattern = @"(\d+)\sPoints";
Regex regex = new Regex(pattern);
Match match = regex.Match(test);
string result = match.Success ? match.Groups[1].Value : "";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.