nibbana
nibbana

Reputation: 729

Regular expression to replace characters after a specific number of commas

I have a string like this:

word1, word2, word3, word4, word5

The result should look like:

word1, word2, word3 . . .

That is, I would like to replace everything that comes after the third comma (third comma included) with

. . .

using the Oracle REGEXP_REPLACE function.

Thanks for any help in advance!

Upvotes: 2

Views: 1808

Answers (3)

Andy Lobel
Andy Lobel

Reputation: 3416

^(([^,]*,){2,2}[^,]*),.*

and replace it with what is found

\1 . . .

I don't have experience with the function but it would probably go like this:

REGEXP_REPLACE(str, '^(([^,]*,){2,2}[^,]*),.*', '\1 . . .')

Upvotes: 1

enenen
enenen

Reputation: 1967

You can use implode and array_slice instead of regular expression:

<?php
$words_to_display = 3;
$str = "word1, word2, word3, word4, word5";

$array = explode(', ', $str);
print_r($array);

$array = array_slice($array, 0, $words_to_display);

$str = implode(', ', $array).' . . .';
echo $str;
?>

Demo: http://ideone.com/TTmPhr

Upvotes: 0

avishayp
avishayp

Reputation: 706

No need in regular expressions or 'design'.

  1. Split on ','

  2. iterate and replace.

  3. Rejoin and rejoice.

Upvotes: 0

Related Questions