Rami Chasygov
Rami Chasygov

Reputation: 2784

Get match with excluded characters

I have text 3571157, 357-11-57, 357 11 57

I can catch these numbers with regex \d{3}[-\s]?\d{2}[-\s]?\d{2}

but what I want is my match look like 3571157 in all cases. Is even possible?

P.S. I mean on regex level, without additional code after, to make more clear in code /[a-z-]+/.exec('ha-ha')[0] I wanna ouput haha (match with excluded - character)

Upvotes: 0

Views: 54

Answers (2)

The fourth bird
The fourth bird

Reputation: 163577

There is no programming language tagged, but if you get the matches from the string you can replace all non digits using \D+ with an empty string leaving only the digits.

An example using Javascript:

let str = "3571157, 357-11-57, 357 11 57";
let pattern = /\d{3}[-\s]?\d{2}[-\s]?\d{2}/g;
console.log(str.match(pattern).map(s => s.replace(/\D+/g, '')));

Upvotes: 1

Emma
Emma

Reputation: 27743

Yes, it is viable. You might do so with a string replace on space and -, such as:

$input = '3571157, 357-11-57,  81749 91741 9080,  81749 91741 9080,  81749 91741 9080  ,357 11 57, 81749 91741 9080';
$split_inputs = preg_split('/,/s', $input);
$output = '';
foreach ($split_inputs as $key => $value) {
    $match = preg_match('/^[0-9 \-]{7,9}$/s', trim($value));
    if (!$match) {continue;}
    $output .= preg_replace('/-|\s/s', '', $value);
    if (sizeof($split_inputs) - 1 - $match != (int) $key) {
        $output .= ", ";
    }
}

var_dump($output);

Output

 string(25) "3571157, 3571157, 3571157"

You may use this RegEx and match your input first.

^[0-9\s\-]{7,9}$

enter image description here

Upvotes: 1

Related Questions