正则表达式使用C#保持未知长度的字符串的最后4个字符

13 c# regex

我需要使用正则表达式来保留字符串的最后4个字符.我不知道字符串的长度所以我需要从最后开始并向后计数.该程序是用c#编写的.

以下是两个示例字符串:

  • 840057
  • 1002945

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

  • 0057
  • 2945

我原来的代码行使用了Regex.Replace,但我找不到正则表达式,因为你可以在下面的评论中看到.

replacementVal = Regex.Replace(replacementVal, wildcard.Regex, wildcard.RegexReplaceBy);
Run Code Online (Sandbox Code Playgroud)

我将代码切换为使用Regex.Match,然后正则表达式(?s)[0-9]{4}$完美运行(见下文):

replacementVal = Regex.Replace(replacementVal, wildcard.Regex, wildcard.RegexReplaceBy);
Run Code Online (Sandbox Code Playgroud)

但是,使用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;
        }
Run Code Online (Sandbox Code Playgroud)

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

Wik*_*żew 11

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

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

所以,当你有一个类似的字符串1002945,并且你想从最后获得4位数时,你可以使用

var result = Regex.Replace("1002945", @".*([0-9]{4})$", "$1", RegexOptions.Singleline);
Run Code Online (Sandbox Code Playgroud)

要么

var matchResult = Regex.Match("1002945", @"[0-9]{4}$");
if (matchResult.Success) 
{
    Console.WriteLine(matchResult.Value);
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 谢谢你的解释.现在一切都运转良好.谢谢 (2认同)

Tim*_*ker 8

.*(?=.{4})$
Run Code Online (Sandbox Code Playgroud)

将匹配字符串的最后四个字符.如果替换匹配String.Empty,则仅剩下这四个字符.

如果字符串包含少于四个字符,它们将保留在字符串中,因为正则表达式根本不匹配,因此无需替换.

  • 你的问题不清楚 - 我们都把它解释为"我想匹配字符串的最后四个字符".您希望匹配除最后四个字符之外的所有字符,并将其替换为空字符串.写一个问题时请具体:) (2认同)