Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove and ID from a string

Tags:

string

regex

perl

I have a string that looks like this, they are ids in a table:

1,2,3,4,5,6,7,8,9

If someone deletes something from the database, I will need to update the string. I know that doing this it will remove the value, but not the commas. Any idea how can I check if the id has a comma before and after so my string doesn't break?

$new_values = $original_values[0];
$new_values =~ s/$car_id//;

Result: 1,2,,4,5,6,7,8,9 using the above sample (bad). It should be 1,2,4,5,6,7,8,9.

like image 555
Pedro Avatar asked Oct 23 '20 20:10

Pedro


3 Answers

To remove the $car_id from the string:

my $car_id = 3;
my $new_values = q{1,2,3,4,5,6,7,8,9}; 
$new_values = join q{,}, grep { $_ != $car_id } 
    split /,/, $new_values; 
say $new_values;
# Prints:
# 1,2,4,5,6,7,8,9

If you already removed the id(s), and you need to remove the extra commas, reformat the string like so:

my $new_values = q{,,1,2,,4,5,6,7,8,9,,,}; 
$new_values = join q{,}, grep { /\d/ } split /,/, $new_values; 
say $new_values;
# Prints:
# 1,2,4,5,6,7,8,9
like image 173
Timur Shtatland Avatar answered Oct 17 '22 05:10

Timur Shtatland


You can use

s/^$car_id,|,$car_id\b//

Details

  • ^ - start of string
  • $car_id - variable value
  • , - comma
  • | - or
  • , - comma
  • $car_id - variable value
  • \b - word boundary.
like image 5
Wiktor Stribiżew Avatar answered Oct 17 '22 07:10

Wiktor Stribiżew


s/^\Q$car_id\E,|,\Q$car_id\E\b//

Another approach is to store an extra leading and trailing comma (,1,2,3,4,5,6,7,8,9,)

The main benefit is that it makes it easier to search for the id using SQL (since you can search for ,$car_id,). Same goes for editing it.

On the Perl side, you'd use

s/,\K\Q$car_id\E,//    # To remove
substr($_, 1, -1)      # To get actual string
like image 5
ikegami Avatar answered Oct 17 '22 06:10

ikegami