Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regex - can I say 'if character/string matches, delete it and all to right of it'?

I have an array of strings, some of which contain the character '-'. I want to be able to search for it and for those strings that contain it I wish to delete all characters to the right of it.

So for example if I have:

$string1 = 'home - London';
$string2 = 'office';
$string3 = 'friend-Manchester';

or something as such, then the affected strings would become:

$string1 = 'home';
$string3 = 'friend';

I don't know if the white-space before the '-' would be included in the string afterwards (I don't want it as I will be comparing strings at a later point, although if it doesn't affect string comparisons then it doesn't matter).

I do know that I can search and replace specific strings/characters using something like:

$string1 =~ s/-//
or 
$string1 =~ tr/-//

but I'm not very familiar with regular expressions in Perl so I'm not 100% sure of these. I've looked around and couldn't see anything to do with 'to the right of' in regex. Help appreciated!

like image 712
dgBP Avatar asked Dec 01 '25 02:12

dgBP


1 Answers

You can delete anything after a hyphen - with this substitution:

s/-.*$//s

However, you will want to remove the whitespace prior to the hyphen and thus do

s/\s* - .* $//xs

The $ anchores the regex at the end of the string and the /s flag allows the dot to match newlines as well. While the $ is superfluous, it might add clarity.

Your substitution would just have removed the first -, and your transliteration would have removed all hyphens from the string.

like image 190
amon Avatar answered Dec 04 '25 22:12

amon