首页 > 解决方案 > 正则表达式使用 C# 保留未知长度字符串的最后 4 个字符

问题描述

我需要使用正则表达式来保留字符串的最后 4 个字符。我不知道字符串的长度,所以我需要从末尾开始倒数。该程序是用 C# 编写的。

下面是两个示例字符串:

我需要的结果是(最后 4 个字符):

我的原始代码行使用了 Regex.Replace 但我找不到可以工作的正则表达式,正如您在下面的评论中看到的那样。

replacementVal = Regex.Replace(replacementVal, wildcard.Regex, wildcard.RegexReplaceBy);

我将代码切换为使用 Regex.Match,然后正则表达式(?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;
        }

非常感谢,感谢您的帮助。

标签: c#regex

解决方案


Regex.Replace方法将所有与正则表达式模式匹配的非重叠子字符串替换为指定的替换。

Regex.Match方法在指定的输入字符串中搜索第一次出现的正则表达式。

所以,当你有一个像 的字符串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);
}

当您替换时,您必须匹配整个字符串,仅匹配并捕获最后四个数字字符,并断言正则表达式索引位于字符串的末尾 ( $)。注意RegexOptions.Singleline选项的使用允许.匹配换行符,默认情况下它不匹配。替换字符串应该是$1,对捕获数字的第一个捕获组的替换反向引用。

当您使用 时Regex.Match("1002945", @"[0-9]{4}$").Value,您将匹配字符串结尾或换行符和字符串结尾后跟的 4 位数字(这是因为$这样的匹配,如果您不想在换行符和字符串结尾之前允许匹配,使用\zmanchor)。获得匹配后,您可以使用 来检查是成功还是失败matchResult.Success,如果有匹配,则获取matchResult.Value。您不再需要RegexOptions.Singleline,因为.正则表达式中没有。


推荐阅读