How can I strip this line with regular expession to
get 12345 number within brackets:
$line = "some text is here (12345 ms)";
This did not work:
$text = $line;
$text =~ m/\((\d+)\)/;
There are some misconceptions,
$text =~ /\((\d+)\)/;
This expression (m is superfluous here)
evaluates in "scalar context", so the (unused)
"return value" is the number of hits (would be
1 in this case if the regex is correct).
If you say BRACKET '(' NUMBER (\d+) BRACKET ')',
the Regex engine thinks you mean it, so if
there is something between NUMBER and BRACKET,
your expression would not match. Better catch
such cases by an expression like:
$text =~ /\( \D* (\d+) \D* \)/x
\D* means 'no number thingy', zero or more times,
/x means 'use formatting' and ignore whitespace
in Regex.
You could do several things now:
- 'in place' replacement of the whole bracket (...)
thing by the number it contains (in $1)
$text =~ s/\( \D* (\d+) \D* \)/$1/x;
which will result in: some text is here 12345
note the s/ (substitution)
- *extract* the number but don't care about the text
my @number = $text =~ /\( \D* (\d+) \D* \)/x;
after this, the array @number has one element: 1234
(here, the expression is evaluated in list context,
returning the matches then)
Of course, there are more variants, but to give
you a start, this should suffice.
Regards
Mirco