tags:

views:

114

answers:

6

Hi, There is a sub to handle the Type and Value.

sub parse_type_value_specifier { 
    my $tvs = shift; 
    my ($type, $value) = $tvs =~ /<(\w+)\s+(.*?)>/;
    return $type, $value; 
}

It should suit for three formats below.

<B 0> - works, return $type = (B) and $value = (0)
<A[1..80] ""> - doesn't work, need return $type = A[1..80] and $value = () # empty
<A[1..80] "hello"> - doesn't work. need return $type = A[1..80] and $value = (hello)

/<(\w+)\s+(.*?)>/ Thank you.

+1  A: 

It sounds like you want to ignore "s. Run it through another regex to strip those out first.

James Polley
+2  A: 

How about

/<([\w\[\].]+)\s*"?([^">]*)"?>/

or /<(\w+)\s*"?([^">]*)"?>/ if your A[1..80] means \w length 1 to 80

S.Mark
This would also allow `<foo ">` or `<foo >"` or `<foo ">"`.
Gumbo
Yeah Gumbo, very correct, since we partially matching "?, I will add another one
S.Mark
@Gumbo. As you said, my A[1..80] means \w length 1 to 80. thank you.
Nano HE
I have changed `\s+` to `\s*` to match `<A[1..80]>`
S.Mark
+2  A: 

Try this:

/<(\w{1,80})\s*(?:\s([^\s">]+|"[^"]*"))?>/

Now if the match of the second grouping starts with a ", remove it from the start and the end and you have the plain value.

Gumbo
+1  A: 

Try this

<(.+) +"?(.*?)"?>
Rubens Farias
+1  A: 

Your regex is 99% correct, problem is that \w will not match literal square braces []. just repace \w with a suitable character class [\w\[\]\.]+

<([\w\[\]\.]+)\s+(.*?)>
Paul Creasey
+2  A: 

The following "works" for the input you show but you should provide a more complete spec:

#!/usr/bin/perl

use strict; use warnings;

while ( <DATA> ) {
    if ( my ($type, $value) = /^<([A-Z])(?:\[.+\])?\s+"?(\w*)"?>/ ) {
        print "\$type = $type\t\$value = $value\n";
    }
}

__DATA__
<B 0>
<A[1..80] "">
<A[1..80] "hello">

Output:

$type = B       $value = 0
$type = A       $value =
$type = A       $value = hello
Sinan Ünür
Hi Sinan, You teached me a good way to do some simple regex practice. Thank you.
Nano HE
btw, Why could the **__DATA__** segment be input to `while (<DATA>)` ?
Nano HE
http://perldoc.perl.org/perldata.html#Special-Literals BTW, `s/teached/taught/`
Sinan Ünür