我需要使用正则表达式来保留字符串的最后4个字符。我不知道绳子的长度,所以我需要从最后开始倒数。程序是用c编写的。
下面是两个字符串示例:840057
1002945
我需要结果是(最后4个字符):0057
2945
我原来的代码行使用正则表达式。替换,但我找不到一个正则表达式工作,你可以在下面的评论中看到。
replacementVal = Regex.Replace(replacementVal, wildcard.Regex, wildcard.RegexReplaceBy);
我将代码转换为使用regex.match,然后regex
(?s)[0-9]{4}$
工作得很好(见下文):replacementVal = Regex.Replace(replacementVal, wildcard.Regex, wildcard.RegexReplaceBy);
但是,使用regex.match会中断我使用的其他正则表达式,例如,我使用
^(.).*
检索名称的第一个字母。这在使用regex.replace时有效,但在使用regex.match时失败。我的代码在下面,请注意包含regex.replace的原始行被注释掉了。
为什么regex.match与一个表达式一起工作,而regex.replace与另一个表达式一起工作?
/// Replaces a wildcard in a string
/// </summary>
/// <param name="str">The string for which to replace the wildcards</param>
/// <param name="row">The DataRow in which the string exists</param>
/// <param name="wildcard">The wildcard to replace</param>
/// <returns>The string with the wildcard replaced</returns>
private static string ReplaceWildcardInString(string str, DataRow row, Wildcard wildcard)
{
// If the string is null or empty, return it as is
if (string.IsNullOrEmpty(str))
return str;
// This will hold the replacement value
var replacementVal = string.Empty;
// If the replacement column value is not empty
if (!row.IsDBNullOrNull(wildcard.ReplaceByColumnName))
{
// Convert its value to string
replacementVal = row[wildcard.ReplaceByColumnName].ToString();
// Apply wildcard regex if given
if (!string.IsNullOrEmpty(wildcard.Regex) && wildcard.RegexReplaceBy != null)
//replacementVal = Regex.Replace(replacementVal, wildcard.Regex, wildcard.RegexReplaceBy);
replacementVal = Regex.Match(replacementVal, wildcard.Regex).Value;
}
// Replace all wildcards with the replacement value (case insensitive)
var wildcardPattern = Regex.Escape(string.Format("%{0}%", wildcard.Name));
str = Regex.Replace(str, wildcardPattern, replacementVal, RegexOptions.Singleline | RegexOptions.IgnoreCase);
// Return the new string
return str;
}
多谢,谢谢你的帮助。
最佳答案
Regex.Replace
method用指定的替换替换替换与正则表达式模式匹配的所有不重叠的子字符串。Regex.Match
method在指定的输入字符串中搜索正则表达式的第一个匹配项。
因此,当您有一个类似1002945
的字符串,并且您希望从末尾精确地得到4位数字时,可以使用
var result = Regex.Replace("1002945", @".*([0-9]{4})$", "$1", RegexOptions.Singleline);
或
var matchResult = Regex.Match("1002945", @"[0-9]{4}$");
if (matchResult.Success)
{
Console.WriteLine(matchResult.Value);
}
替换时,必须匹配整个字符串,只匹配并捕获最后四个数字字符,并断言regex索引位于字符串末尾(
$
)。注意使用RegexOptions.Singleline
option允许.
匹配newline char,默认情况下不匹配。替换字符串应该是$1
,即对捕获数字的第一个捕获组的替换回引用。当您使用
Regex.Match("1002945", @"[0-9]{4}$").Value
时,您将匹配后跟字符串结尾或换行符和字符串结尾的4位数字(这是因为$
这样匹配,如果您不希望在换行符和字符串结尾之前允许匹配,请使用\z
manchor)。当获得匹配时,可以使用matchResult.Success
检查它是成功还是失败,如果有匹配,得到matchResult.Value
。您不再需要RegexOptions.Singleline
,因为regex中没有.
。