RegEx to swap only the first 2 digits of a middle part of a string? -
i seem have quite difficult task ahead need solve xquery , regular expressions.
the case: have alphanumeric string variable length of 20 30 chars first 2 digits of middle part (char 5 char(length-5)) of string should swapped , if there no or 1 digit in middle part 10th , 11th char of string should swapped.
so, few examples:
string: abcde12345fghij67890 (more 1 digit) output: abcde21345fghij67890 (swap first 2) string: 1a2b3c4d5e6f7g8h9i0j1k2l3m4 (more 1 non adjacent digits) output: 1a2b3c5d4e6f7g8h9i0j1k2l3m4 (swap first 2 of middle part) string: 34gf7asjkabaa4sfdlencxnkil9qrx (only 1 digit in middle part) output: 34gf7asjkbaaa4sfdlencxnkil9qrx (so, swap char 10 , 11) my pseudocode this:
function changestring(orgstring) newstring:=replace(orgstring, regex-1st-digits-in-middle-pattern, regex-swap) if newstring=orgstring #when there no 2 digits swap newstring:=replace(orgstring, regex-10/11char, regex-swap) return newstring i reckon there's no way whole solution in 1 line, that's why came above pseudocode. should correct find , replace regular expressions?
thanx in advance!
edit: forgot 1 thing in pseudocode... prevent swap of 10/11th char when first 2 digits of middle-string same number...
my pseudocode of course this:
string: whatever4any4any567whatever output: whatever4nay4any567whatever so need change compare this:
if count(digits in middlestring) < 2
in pseudocode:
function changestring(orgstring) newstring:=replace(orgstring, "^(.{5})(\d*)(\d)(\d*)(\d)(.*)(.{5})$", "$1$2$5$4$3$6$7") if newstring=orgstring #when there no 2 digits swap newstring:=replace(orgstring, "^(.{9})(.)(.)(.*)$", "$1$3$2$4") return newstring explanation of first regex:
^ # anchor match start of string (.{5}) # match 5 characters, save them in backreference $1 (\d*) # match number of non-digits, save in $2 (\d) # match 1 digit, save in $3 (\d*) # match number of non-digits, save in $4 (\d) # match 1 digit, save in $5 (.*) # match number of characters, save in $6 (.{5}) # match 5 characters, save in $7 $ # anchor match end of string test first regex on regex101.com.
test second regex on regex101.com.
Comments
Post a Comment