RegEx替换前缀和后缀

时间:2015-04-19 13:01:00

标签: regex

我想构建一个RegEx表达式来替换字符串的前缀和后缀。一般字符串是从

构建的
  1. 已知前缀字符串
  2. 某些字母a-z或A-Z
  3. 一些带有字母,连字符,反斜杠,斜线和数字的未知字符串。
  4. 连字符
  5. 整数
  6. 符号#。
  7. 一些字母串
  8. 示例:

    KnownStringr/df-2e\d-3724#.Gkjsu
    KnownStringEd\e4v-bn-824#.YKfg
    KnownStringa-YK224E\yy-379924#.awws
    

    我想替换NUMBER的前缀和后缀,以便我得到:

    MyPrefix3724MyPostfix
    MyPrefix824MyPostfix
    MyPrefix379924MyPostfix
    

1 个答案:

答案 0 :(得分:0)

这个正则表达式应该可以解决问题,但是你总是应该指定你正在使用的语言/框架,因为并非所有正则表达式引擎都支持相同的功能。

您要捕获的数字将位于捕获组#3((\d+))中,大多数语言都将其引用为\ 3

(?:KnownString)([a-zA-Z])(.*?)-(\d+)\#\.[a-zA-Z]+

说明:

 (?:                     # Opens NCG
     KnownString         # Literal KnownString
 )                       # Closes NCG
 (                       # Opens CG1
     [a-zA-Z]            # Character class (any of the characters within)
                           # Anything between a and z
                           # Anything between A and Z
 )                       # Closes CG1
 (                       # Opens CG2
     .*?                 # . denotes any single character, except for newline
                           # * repeats zero or more times
                           # ? as few times as possible
 )-                      # Closes CG2
                           # Literal -
 (                       # Opens CG3
     \d+                 # Token: \d (digit)
                           # + repeats one or more times
 )                       # Closes CG3
 \#                      # Literal #
 \.                      # Literal .
 [a-zA-Z]+               # Character class (any of the characters within)
                           # Anything between a and z
                           # Anything between A and Z
                           # + repeats one or more times

您还没有指定已知前缀的内容,您应该小心转义已知字符串中的特殊字符,尤其是句点,加号,星号,问号和括号。