Home > database >  RegEx expression for removing duplicates and all numbers and brackets
RegEx expression for removing duplicates and all numbers and brackets

Time:08-10

So if I have a string that looks like this:

{1}{G}{G}{U}{U}{W}

I'd like the result to be:

GUW

I currently have this as my regex:

/(.)(?=.*\1)[^GUW]/

I also would like to pick the characters that would be used. In this case, 'GUW'.

CodePudding user response:

You might use 2 capture groups, where you would optionally repeat backreference to group 1 value (with the curly's) and use a replacement with group 2 that has the value inside the curly's.

The character class [GUW] matches one of the listed chars to be matched.

The dot after the | would match any other character to be removed.

(\{([GUW])})\1*|.

Regex demo | PHP demo

For example:

$re = '/(\{([GUW])})\1*|./';
$str = '{1}{G}{G}{U}{U}{W}';
$result = preg_replace($re, '$2', $str);

echo $result;

Output

GUW
  • Related