我前面似乎有一项非常困难的任务,需要用xQuery和正则表达式来解决。
情况:我有一个字母数字字符串,可变长度为20到30个字符,其中只有中间部分的前2位数字(字符5到字符(长度-5))应该被交换,如果中间部分没有或只有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我想大概没有办法把整个解决方案写成一行,所以我想出了上面的伪代码。但是正确的查找和替换正则表达式应该是什么呢?
提前鸣谢!
编辑:我在我的伪码里忘了一件事.这是为了防止当中间字符串的前2位是相同的数字时,10/11字符的交换.
我的伪码当然会这么做:
String: whatever4any4any567whatever
Output: whatever4nay4any567whatever所以,我需要改变这个比较,比如:
if count(digits in middlestring) < 2发布于 2015-07-08 17:23:56
感谢西德尔的作者
replace(OrgString, "^(.{5})((.*?)([0-9])(.*?)([0-9])(.*)|(.{6})(.)(.)(.*))(.{5})$",
"$1$3$6$5$4$7$8$10$9$11$12")发布于 2015-07-08 09:32:42
在你的伪码里:
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:
^ # 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。
https://stackoverflow.com/questions/31288186
复制相似问题