i am trying to write a regular expression so i can replace following phone numbers with a link:
first
+45 55 44 33 22
second
+4555443322
third
+45 55443322
fourth
55443322
and last
55 44 33 22
currentley my regular expression looks like this:
Regex phoneRegex = new Regex(@"[0-9]{8}", RegexOptions.IgnoreCase);
Regex phoneRegexInternation = new Regex(@"(?:\+\[0-9]{10})", RegexOptions.IgnoreCase);
Regex phoneRegexwithSpace = new Regex(@"[0-9]{2}\s*[0-9]{2}\s*[0-9]{2}\s*[0-9]{2}", RegexOptions.IgnoreCase);
Regex phoneRegexInternationWithSpaceAfterAreaCode = new Regex(@"(\+?[0-9]{2})\s*[0-9]{8}", RegexOptions.IgnoreCase);
Regex phoneRegexwithSpaceInternational = new Regex(@"(\+?[0-9]{2})\s*[0-9]{2}\s*[0-9]{2}\s*[0-9]{2}\s*[0-9]{2}", RegexOptions.IgnoreCase);
but my result i this
first +Acceptere opgaven for at se telefonnummer. 22 second +Acceptere opgaven for at se telefonnummer.22 third +45 Acceptere opgaven for at se telefonnummer. fourth Acceptere opgaven for at se telefonnummer. and last Acceptere opgaven for at se telefonnummer.
"Acceptere opgaven for at se telefonnummer" is a danish expression for accept the assignment to see the phonenumber and it's a link, but as you can se it's not hiding the plus sign and a few of the numbers correctley.
anyone that can help?
答案 0 :(得分:0)
var input = @"first
+45 55 44 33 22
second
+4555443322
third
+45 55443322
fourth
55443322
and last
55 44 33 22";
var regex = new Regex(@"(?<inter>\+45\s?)?(?<part1>\d{2})\s?(?<part2>\d{2})\s?(?<part2>\d{2})\s?(?<part4>\d{2})");
var matches = regex.Matches(input);
var output = new StringBuilder();
var lastindex = 0;
var index = 0;
foreach (Match m in matches){
index = m.Index;
output.Append(input.Substring(lastindex, index - lastindex));
var phone = $"+45{m.Groups["part1"]}{m.Groups["part2"]}{m.Groups["part3"]}{m.Groups["part4"]}";
output.Append($"<a href=\"#\" data-original=\"{m.Value}\" data-generic=\"{phone}\">Acceptere opgaven for at se telefonnummer</a>");
lastindex = m.Index + m.Length;
}
Console.WriteLine(output.ToString());
结果是:
first
<a href="#" data-original="+45 55 44 33 22" data-generic="+45553322">Acceptere opgaven for at se telefonnummer</a>
second
<a href="#" data-original="+4555443322" data-generic="+45553322">Acceptere opgaven for at se telefonnummer</a>
third
<a href="#" data-original="+45 55443322" data-generic="+45553322">Acceptere opgaven for at se telefonnummer</a>
fourth
<a href="#" data-original="55443322" data-generic="+45553322">Acceptere opgaven for at se telefonnummer</a>
and last
<a href="#" data-original="55 44 33 22" data-generic="+45553322">Acceptere opgaven for at se telefonnummer</a>
答案 1 :(得分:0)
如果没有看到你如何应用这些正则表达式,很难确定你在做什么。了解您期望看到的内容也很有帮助。那就是说,我会尽力回答。
基于正则表达式,输入和输出,您可能无意中将错误的正则表达式应用于错误的输入。如前所述,我们无法确切知道您是如何使用它们的。请注意,phoneRegexWithSpace将匹配第一个输入,除了+和22,它们都会在输出中弹出不需要的内容。
要纠正它,你可以做一些事情: