你想要做的是,儘管可能,使用一個單一的正則表達式模式有點複雜。您可以將這種情況分解成更小的步驟。其中一種方法是提取Username
和Domain
組(基本上就是您所描述的[any character]
),「修復」每個組,並將其替換爲原始組。事情是這樣的:
// Original input to transform.
string input = @"[email protected] r&a*[email protected]@company98 ';99..com";
// Regular expression to find and extract "Username" and "Domain" groups, if any.
var matchGroups = Regex.Match(input, @"employee(?<UsernameGroup>(.*))@company(?<DomainGroup>(.*)).com");
string validInput = input;
// Get the username group from the list of matches.
var usernameGroup = matchGroups.Groups["UsernameGroup"];
if (!string.IsNullOrEmpty(usernameGroup.Value))
{
// Replace non-alphanumeric values with empty string.
string validUsername = Regex.Replace(usernameGroup.Value, "[^a-zA-Z0-9]", string.Empty);
// Replace the the invalid instance with the valid one.
validInput = validInput.Replace(usernameGroup.Value, validUsername);
}
// Get the domain group from the list of matches.
var domainGroup = matchGroups.Groups["DomainGroup"];
if (!string.IsNullOrEmpty(domainGroup.Value))
{
// Replace non-alphanumeric values with empty string.
string validDomain = Regex.Replace(domainGroup.Value, "[^a-zA-Z0-9]", string.Empty);
// Replace the the invalid instance with the valid one.
validInput = validInput.Replace(domainGroup.Value, validDomain);
}
Console.WriteLine(validInput);
將輸出[email protected]
。
正則表達式本身會做你所需要的東西(除了它會刪除'@'和''') - 它只取決於你的編程語言你應該如何使用它。從'var'我認爲JavaScript? – dognose 2014-10-29 20:53:02
爲什麼它應該成爲「[email protected]」而不是「[email protected].m32company9899.com」? – Oriol 2014-10-29 20:56:18
@Oriol OP的第二和第三行應該回答你的問題......這始終是開始的格式,我們想用它做什麼。 「@company」始終是電子郵件域的開始。 – chrismat 2014-10-29 21:00:39