Hello all.
I have a small problem, the next code finds the neden content, but it doenst print it:

$string = "#324423asdd asd 'BecamePosters' ";
if($string =~ m/'[a-zA-Z]{1,40}'/) {
print "ok!\n";
print $1;
} else {
print "not ok!\n";
}

It only prints "ok!\n" but nothing more.
Also triyed m/'*'/ but i get the same result, any sujestions ?

Dani AI

Generated

The reason you saw "ok!" but nothing after it is that the regex matched but you never created a capture group, so $1 was never set. As noted, wrapping the part you want in parentheses populates $1. That explains the behavior: the match operator returns true/false, but only parenthesized subpatterns fill $1, $2, etc.

For a more robust way to extract text between single quotes (and to handle multiple quoted items), capture only the inner text and iterate with /g. This avoids accidentally including the quotes and prevents a single big match from spanning multiple quoted segments:

use strict;
use warnings;

my $string = q{#324423asdd asd 'BecamePosters' and 'OtherOne'};

while ( $string =~ /'([^']{1,40})'/g ) {
    print "$1\n";
}

Notes and troubleshooting tips:

  • Use [^'] to stop at the next single quote; this prevents a greedy match from jumping past an intermediate quote.
  • If quoted content may contain escaped quotes, use a pattern that allows \' (for example /'((?:[^'\\]|\\.){1,40})'/).
  • To match Unicode letters instead of ASCII only, use \p{L} with the u modifier.
  • If you only need a single capture and dont want extra capture numbering altered by helper groups, use non-capturing groups (?:...) for parts you don't want in $1.
  • For parsing more complex or nested structures (HTML, CSV with quoted fields, or nested quotes), consider a proper parser or Text::ParseWords instead of ad-hoc regexes.

This complements ’s fix by showing how to extract multiple matches safely and how to tweak the pattern for escaped quotes or Unicode.

Recommended Answers

All 2 Replies

#!/usr/bin/perl -w
use strict;
my $string = "#324423asdd asd 'BecamePosters' ";
if($string =~ m/('[a-zA-Z]{1,40}')/) { #Put parentheses around what should be $1
print "ok!\n";
print $1;
} else {
print "not ok!\n";
}

Ty vm =)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.