Search code examples
arraysstringperlwww-mechanizewww-mechanize-firefox

How to find a word beginning with specified letters then remove everything else in the string?


my @buildno = $mech->xpath('/html/body/form/table/tbody/tr[2]/td[3]/table
/tbody/tr[2]/td/table/tbody/tr[1]/td/table/tbody/tr[1]/td', type => 
$mech->xpathResult('STRING_TYPE'));

I have the above code which contains a string. I need to capture the word beginning with CSR contained in the array within a string. There is only one element @buildno[0]. I need to keep the word and remove everything else in the string. I have tried using the m// way however it only returns a boolean telling me that the word exists. I have also tried subtituting s/// however I can only remove the word that I need to keep, I cannot figure out a way to reverse that function.

EDIT I have managed to split the string up and put it into a new array so each word is a seperate index.

my $buildno = join('', @buildno);
my @build = split(' ',$buildno);
print @build[1];

The word I am looking for in this instance is the second element in the array as it is the second word @build[1]however the word may not always be the second word in the string, it could be the fourth word for example. My purpose is to capture that specific word for later use.


Solution

  • You may match the desired word using m// storing it in a capture group and then replace the whole original string with that matched group:

    do {$_ = $1 if /(?:^|\s)(CSR\S*)/} foreach @buildno;
    

    Demo: https://ideone.com/1l7YJb