LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Help building a regular expression for use in split function? (https://www.linuxquestions.org/questions/linux-newbie-8/help-building-a-regular-expression-for-use-in-split-function-872411/)

mrm5102 04-01-2011 11:16 AM

Help building a regular expression for use in split function?
 
Hey all,

I am a semi-new user to linux and could use some help building a regular expression for use in a split function.

Ok, so I have a perl script that contains an array like this:

@hostNames = (ABC123R:192.168.1.1, CBA321CBP:192.168.1.2, ZYX987R:192.168.1.3, etc...)

Where for example the first element "ABC123R:192.168.1.1":
ABC123R is the hostname and 192.168.1.1 is it's IPaddress.

I am trying to write a regular expression that will split the element with a '-' wherever there is a LETTER next to a NUMBER, like so:
ABC-123-R:192.168.1.1

I tried this expression below but am struggling with using regex for slightly complicated matching criteria:

for ($x = 0; $x < scalar(@hostNames); $x++)
{
$hostNames[$x] = split /([A-Z][0-9])/, "-"
}

markush 04-01-2011 04:01 PM

Hello mrm5102, welcome to LQ,
Code:

#!/usr/bin/perl -w

use strict;

my $zeile="ABC123R:192.168.1.1, CBA321CBP:192.168.1.2, ZYX987R:192.168.1.3";
$zeile =~ s/([A-Z])([0-9])/$1-$2/g;
$zeile =~ s/([0-9])([A-Z])/$1-$2/g;
print $zeile, "\n";

this will work for you.

Markus

mrm5102 04-04-2011 08:30 AM

Awesome, that did the trick. Thanks so much!


All times are GMT -5. The time now is 10:57 PM.