RegEx只交换字符串中间部分的前2位数?

时间:2015-07-08 09:09:04

标签: regex string replace xquery

我需要用xQuery和正则表达式来解决这个问题。

案例:我有一个ALPHANUMERIC字符串,其VARIABLE长度为20到30个字符,其中只有字符串的MIDDLE部分(字符5到字符(长度为5))的FIRST 2 DIGITS应该是SWAPPED,如果有的话在这个MIDDLE部分中,NO或只有1位数字应该交换字符串的第10个和第11个字符。

所以,举几个例子:

String: abcde12345fghij67890            (more than 1 digit)
Output: abcde21345fghij67890            (swap only first 2)

String: 1a2b3c4d5e6f7g8h9i0j1k2l3m4     (more than 1 non adjacent digits)
Output: 1a2b3c5d4e6f7g8h9i0j1k2l3m4     (swap only first 2 of middle part)

String: 34gf7asjkabaa4sfdlencxnkil9qrx  (only 1 digit in middle part)
Output: 34gf7asjkbaaa4sfdlencxnkil9qrx  (so, swap char 10 and 11)

我的伪代码是这样的:

Function ChangeString(OrgString) 
  NewString:=replace(OrgString, RegEx-1st-digits-in-middle-pattern, RegEx-swap)
  if NewString=OrgString #when there were no 2 digits to swap
    NewString:=replace(OrgString, RegEx-10/11char, RegEx-swap)
  return NewString

我认为可能无法在1行中获得整个解决方案,所以这就是我想出上述伪代码的原因。但是正确的查找和替换正则表达式应该是什么?

提前Thanx!

编辑:我忘记了我的伪代码中的一件事......当中间字符串的前两位数字是相同的数字时,这是为了防止交换10/11的字符...

我的伪代码当然会这样做:

String: whatever4any4any567whatever
Output: whatever4nay4any567whatever

所以我需要将比较改为这样的事情:

if count(digits in middlestring) < 2

2 个答案:

答案 0 :(得分:1)

在您的伪代码中:

Function ChangeString(OrgString) 
  NewString:=replace(OrgString, "^(.{5})(\D*)(\d)(\D*)(\d)(.*)(.{5})$", "$1$2$5$4$3$6$7")
  if NewString=OrgString #when there were no 2 digits to swap
    NewString:=replace(OrgString, "^(.{9})(.)(.)(.*)$", "$1$3$2$4")
  return NewString
第一个正则表达式的

解释

^      # Anchor the match to the start of the string
(.{5}) # Match any five characters, save them in backreference $1
(\D*)  # Match any number of non-digits, save in $2
(\d)   # Match exactly one digit, save in $3
(\D*)  # Match any number of non-digits, save in $4
(\d)   # Match exactly one digit, save in $5
(.*)   # Match any number of characters, save in $6
(.{5}) # Match any five characters, save in $7
$      # Anchor the match to the end of the string

测试第一个正则表达式on regex101.com

测试第二个正则表达式on regex101.com

答案 1 :(得分:0)

感谢dynamic的作者:

{{1}}

测试:Xidel