正则表达式的长度和替换

时间:2014-04-02 15:21:01

标签: regex

我需要一个正则表达式来匹配下面提到的条件

我需要只使用1个REGEX来满足所有条件,请提供任何帮助

我想将BTN改为像这样的德语格式

from : 004171511326 to->494171511326  (BTN starts with '00' and length of BTN is 12)

from : 01777203102  to->491777203102  (BTN starts with '0' and length of BTN is 11)

from : 1772576210   to->491772576210  (Length of BTN is 10)

from : 015732888810 to->491573288881  (BTN starts with '0' and length of BTN is 12 )

2 个答案:

答案 0 :(得分:0)

两个正则表达式。可能不应该进一步考虑因素。


使用分支重置 -

查找:\b(?|00(\d{10})|0(\d{10})\d?|(\d{10}))\b
替换:49$1

 \b 
 (?|
      00 
      ( \d{10} )         # (1)
   |  
      0 
      ( \d{10} )         # (1)
      \d? 
   |  
      ( \d{10} )         # (1)
 )
 \b 

使用群集组 -

查找:\b(?:00(\d{10})|0(\d{10})\d?|(\d{10}))\b
替换:49$1$2$3

 \b 
 (?:
      00 
      ( \d{10} )         # (1)
   |  
      0 
      ( \d{10} )         # (2)
      \d? 
   |  
      ( \d{10} )         # (3)
 )
 \b 

输出>>

 from : 004171511326      to-> 494171511326
 from : 01777203102       to-> 491777203102
 from : 1772576210        to-> 491772576210
 from : 015732888810      to-> 491573288881

Dot-Net C#测试用例

 Console.WriteLine(Regex.Replace("004171511326", @"\b(?:00(\d{10})|0(\d{10})\d?|(\d{10}))\b", @"49$1$2$3"));
 Console.WriteLine(Regex.Replace("01777203102",  @"\b(?:00(\d{10})|0(\d{10})\d?|(\d{10}))\b", @"49$1$2$3"));
 Console.WriteLine(Regex.Replace("1772576210",   @"\b(?:00(\d{10})|0(\d{10})\d?|(\d{10}))\b", @"49$1$2$3"));
 Console.WriteLine(Regex.Replace("015732888810", @"\b(?:00(\d{10})|0(\d{10})\d?|(\d{10}))\b", @"49$1$2$3"));

输出>>

 494171511326
 491777203102
 491772576210
 491573288881

答案 1 :(得分:0)

经过两天的搔痒,我终于找到了解决方案:

(?(^\d{12}$)(?(^0[1-9])0?(?<digit>.{10})|\d*(?<digit>.{10}))|\d*(?<digit>.{10}))

与SQL查询完全相同+始终在Group [1]中给出结果所以我没有必要稍微更改代码。