Remove unwanted character in string using regex

Viewed 195

I'm trying to remove characters that do not match a specific pattern using the example below:

Pattern to match exactly 4 alphabets [a-zA-Z]{4} followed by space(s) \s{1,} then 4 characters starting with an alphabet, last 3 number [a-zA-Z]{1}[0-9]{3}

If I supply ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501 it matches all except Q799, now, I need to remove/replace Q799 from the string.

I tried to apply Negated Character Classes but still not getting the desired result.

$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
$string = preg_replace("/[^a-zA-Z]{4}\s{1,}[a-zA-Z]{1}[0-9]{3}/","",$mystring);

echo $string; //ABEH A501; BIOL L340; BIOL Z; ABEH A501

The desired result should be ABEH A501; BIOL L340; BIOL Z620; ABEH A501

Q799 was removed so also was part of another matching string, not sure if this was due to wrong regEx or wrong application of negated character class.

2 Answers

In PHP you can define a known good match regex and use PCRE verbs (*SKIP)(*F) to skip these matches in replacement:

$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
echo preg_replace('/[a-zA-Z]{4}\s+[a-zA-Z]\d{3}(*SKIP)(*F)|\w+\W*/', '', $mystring);

RegEx Demo

Output:

ABEH A501; BIOL L340; BIOL Z620; ABEH A501

PHP Code Demo

This is a different approach to the question, but hey, it works

<?php

$mystring = "ABEH A501; BIOL L340; BIOL Z620; Q799; ABEH A501";
preg_match_all("/[a-zA-Z]{4}\s{1,}[a-zA-Z]{1}[0-9]{3};?\s+?/",$mystring, $matches);
$result = "";
foreach($matches[0] as $match) {
    $result = $result.$match;
}
echo $result; //ABEH A501; BIOL L340; BIOL Z620; 

?>
Related