首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RegEx只交换字符串中间部分的前2位数字?

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

Stack Overflow用户
提问于 2015-07-08 09:09:03
回答 2查看 696关注 0票数 1

我前面似乎有一项非常困难的任务,需要用xQuery和正则表达式来解决。

情况:我有一个字母数字字符串,可变长度为20到30个字符,其中只有中间部分的前2位数字(字符5到字符(长度-5))应该被交换,如果中间部分没有或只有1位数字,则应该交换字符串的第10和第11位。

因此,有几个例子:

代码语言:javascript
复制
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)

我的伪码是这样的:

代码语言:javascript
复制
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

我想大概没有办法把整个解决方案写成一行,所以我想出了上面的伪代码。但是正确的查找和替换正则表达式应该是什么呢?

提前鸣谢!

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

我的伪码当然会这么做:

代码语言:javascript
复制
String: whatever4any4any567whatever
Output: whatever4nay4any567whatever

所以,我需要改变这个比较,比如:

代码语言:javascript
复制
if count(digits in middlestring) < 2
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-07-08 17:23:56

感谢西德尔的作者

代码语言:javascript
复制
replace(OrgString, "^(.{5})((.*?)([0-9])(.*?)([0-9])(.*)|(.{6})(.)(.)(.*))(.{5})$",
                   "$1$3$6$5$4$7$8$10$9$11$12")

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

票数 0
EN

Stack Overflow用户

发布于 2015-07-08 09:32:42

在你的伪码里:

代码语言:javascript
复制
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

第一个正则表达式的Explanation

代码语言:javascript
复制
^      # 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

测试第一个regex 关于regex101.com

测试第二个regex 关于regex101.com

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31288186

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档