How to remove and ID from a string

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.

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

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

Tags:

String

Regex

Perl