문제

I would like to know if there's a way to save a word in a scalar and then use the scalar in a regex with symbols like "^", "$" in order to evaluate only that word and not a part of it.

This is my code :

@syn = qw(
    abondamment,beaucoup,immensément
    chose,objet,cause
    objet,chose
    ensemble,totalité,tout,unité
    lit,coucher
    ossimor);

@words = qw(
        chose
        os
        totalité
        lit
        absolu);


foreach $w (@words){
    for ($i = 0; $i < @syn; $i++){
        if ( $syn[$i] =~ /$w/){ 
            print "$w : $syn[$i]\n";
            }
        }
    $w++;
}

The output is :

chose : chose,objet,cause chose : objet,chose os : chose,objet,cause os : objet,chose os : ossimor totalité : ensemble,totalité,tout,unité lit : ensemble,totalité,tout,unité lit : lit,coucher

As you can see "$w" matches, for ex., "chose" but also "os". I'd like an output like that:

chose : chose,objet,cause chose : objet,chose totalité : ensemble,totalité,tout,unité lit : lit,coucher

I've tried to write the regex as /^$w$/ but it doesn't work. Any ideas?

도움이 되었습니까?

해결책

Use this regex:

 /\b$w\b/

Word boundaries http://perldoc.perl.org/perlre.html

From http://www.regular-expressions.info/wordboundaries.html :

There are three different positions that qualify as word boundaries:

- Before the first character in the string, if the first character is a word character.
- After the last character in the string, if the last character is a word character.
- Between two characters in the string, where one is a word character and the other is not a word character.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top