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

RegEx to swap only the first 2 digits of a middle part of a string?

我似乎有一个相当困难的任务,我需要用 xQuery 和正则表达式来解决。

案例:我有一个 ALPHANUMERIC 字符串,其可变长度为 20 到 30 个字符,其中只有字符串的中间部分(char 5 到 char(length-5))的前 2 个数字应该被交换并且如果中间部分没有或只有 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 行中获得整个解决方案,所以这就是我想出上述伪代码的原因。但是正确的查找和替换正则表达式应该是什么?

提前致谢!

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

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

String: whatever4any4any567whatever
Output: whatever4nay4any567whatever

所以我需要将比较更改为这样的内容:

if count(digits in middlestring) < 2

在你的伪代码中:

Function ChangeString(OrgString) 
  NewString:=replace(OrgString, "^(.{5})(\D*)(\d)(\D*)(\d)(.*)(.{5})$", "")
  if NewString=OrgString #when there were no 2 digits to swap
    NewString:=replace(OrgString, "^(.{9})(.)(.)(.*)$", "")
  return NewString

第一个正则表达式的解释

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

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

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

感谢Xidel的作者:

replace(OrgString, "^(.{5})((.*?)([0-9])(.*?)([0-9])(.*)|(.{6})(.)(.)(.*))(.{5})$",
                   "")

测试:https://regex101.com/r/fM9dP1/3