0

I am trying to split and re-concatenate a string to get a snippet of a URI.

I start from a simple ID of 16 characters and I have to divide it into 8 pairs of characters, for example from 0b00271180119cce to 0b/00/27/11/80/11/9c/ce/

Is there any way to achieve this using only a RegEx instruction?

Using something like ([A-z0-9]{1,2}) I got a group with 8 matches but I don't know how to recombine them into a string with a separator ("/" in this specific case).

I am afraid that none of the indications below are directly usable in my context. The problem is that I can't use any of the usual programming languages (Java, JavaScript, PHP and so on), because the RegEx instruction has to be used inside a parameter in a Documentum D2 configuration (an Autonaming, to be exact ).

Thanks in advance!

  • `ce7` is a typo? Where does 7 come from? Seems liike https://regex101.com/r/28SioG/1 should work... assuming there is a typo – user3783243 May 02 '23 at 18:13
  • 1
    There are duplicated and unwanted characters (```[`\]^_```) in the `[A-zA-z-0-9]` class. Use `[A-Z0-9]` with the `i` flag, or, if that's not possible, `[A-Za-z0-9]`. – InSync May 02 '23 at 18:47
  • Try `(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)` – Bohemian May 02 '23 at 19:04

2 Answers2

1

Given:

const id = "0b00271180119cce";

use the regex below:

const regex = /([A-Z0-9]{2})/ig;
  • Note: this regex avoids duplicated and unwanted characters as mentioned in another user's comment on your question, but for this case const regex = /([a-zA-Z0-9]{2})/g; would have also worked.

Option 1

The simplest way to match the regex and recombine into a string with a separator ("/" in this specific case) is using a regex replace and inserting the matched capture group followed by a slash into the output string. Here's an example in JavaScript:

const result = id.replace(regex, "$1/");
  • Note: above uses $n where n is the group number

Option 2

You can also achieve this using a regex replace with a function as the second argument:

const result = id.replace(regex, (match, group) => `${group}/`);
  • Note: a function is overkill if you just want to copy the match or capture group into the replacement, so go with option 1. This is just demonstrating an alternative way to accomplish your goal.

You can console.log both results to observe the desired output:

console.log(result); // "0b/00/27/11/80/11/9c/ce/"

const id = "0b00271180119cce";
const regex = /([A-Z0-9]{2})/ig;

let result = id.replace(regex, "$1/");
console.log(result);

result = id.replace(regex, (match, group) => `${group}/`);
console.log(result);
user7247147
  • 1,045
  • 1
  • 10
  • 24
1

Use a back-reference in the replacement string. $& refers to what was matched by the regexp.

let string = '0b00271180119cce';
let new_string = string.replace(/.{1,2}/g, '$&/');
console.log(new_string);
Barmar
  • 741,623
  • 53
  • 500
  • 612