[英]how to extract date from a string using regex
im looking for regex which can extract the date from the following html 我正在寻找可以从以下html中提取日期的正则表达式
<p>British Medical Journal, 29.9.12, pp.37-41.</p>
and convert it in the format 29/09/12 并将其转换为格式29/09/12
Match this pattern: - 匹配此模式:-
(\d+)[.](\d+)[.](\d+)
and replace with: - 并替换为:-
$1/$2/$3
\\d
is used to match digits
. \\d
用于匹配digits
。 Using it with quantifier (+)
, you would match one or more digits. 将其与量词
(+)
配合使用,您将匹配一个或多个数字。 Now, in regex, a dot(.)
is a metacharacter, that matches any character. 现在,在正则表达式中,
dot(.)
是一个元字符,可以匹配任何字符。 To match a period
literally, you would need to either escape it, or use it inside a character class. 要从字面上匹配一个
period
,您需要对其进行转义,或者在字符类中使用它。
To convert to a specific Date Format
, eg: - convert 9
-> 09
, you can make use of a MatchEvaluator
: - 要转换为特定的
Date Format
,例如: MatchEvaluator
9
> 09
,可以使用MatchEvaluator
:-
string input = "British Medical Journal, 29.9.12, pp.37-41.";
Regex reg = new Regex(@"(\d+)[.](\d+)[.](\d+)");
string result = reg.Replace(input, delegate(Match m) {
return m => DateTime.Now.ToString("dd/MM/yy")
});
You can check whether it works or not. 您可以检查它是否有效。
Here is the regex pattern: \\d{1,2}\\.\\d{1,2}\\.\\d{1,2}
. 这是正则表达式模式:
\\d{1,2}\\.\\d{1,2}\\.\\d{1,2}
。
And here is the example of how to parse this string to DateTime: 这是如何将此字符串解析为DateTime的示例:
DateTime.ParseExact("29.9.12", "d.M.yy", CultureInfo.InvariantCulture);
(\\d{4})[-](\\d{2})[-](\\d{2})
使用此正则表达式选择2017年1月23日的格式日期
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.