Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to find a word including same two letter?

Status
Not open for further replies.

whygh

Programmer
Apr 18, 2005
16
CA
in regular expression, how to find a word including same two letter? like hello,wall, google?
 
Thanks. I tried it. the result is
1)
$var="hello";
$var =~ /(.)\1/;
print "$var\n";

the output is "hello"
2)
$var="very";
$var =~ /(.)\1/;
print "$var\n";

the output is "very"

3)
$var="hello";
$var =~ /(.)\1/;
print "$&\n";

the output is "ll"

I want to get the whole word which has two same letters.How do I do? By the way, can you tell me the meaning of "\1"

Thanks again

 
you can add a condition:

Code:
my $var = "hello";
print $var if ($var =~ /(.)\1/);

my $var2 = "test";
print $var2 if ($var2 =~ /(.)\1/);

\1 is whats stored in ()
 
I thought I'd have a little go for you:

Code:
#!/usr/bin/perl -w

use strict;

while(<>) {
  chomp;
  print "$1\n" if(/\b(\w*(\w)\w*\2\w*)\b/);
}

This only finds the first word on the line but it wouldn't be that hard to expand if you need to.

Do you want vowels included as well in this selection?

As in "room"?

Trojan
 
I got bored so I expanded it to do all words on a line.

Code:
#!/usr/bin/perl -w

use strict;

while(<>) {
  chomp;
  my @words = split;
  my $found = 0;
  foreach my $word (@words) {
    if($word =~ /\b(\w*(\w)\w*\2\w*)\b/) {
      print "$1 ";
      $found++;
    }
  }
  print "\n" if($found);
}

BTW: You ought to also consider if a capitalised word should be handled such as "Tint". If you need this then you should add the /i switch to the regex.

Trojan
 
Thanks. It get the right result.
but it has a little bit problem,for explample:

test="lolgh";
print "$1\n" if($test=~/\b(\w*(\w)\w*\2\w*)\b/);

it also match.I need just match like "hello,wall,room".


This is another regular experssion,it works.


$var1="20-20-20";
print $var1 if($var1=~/(\d{2})([\W])\1\2\1/);

"\1" is (\d{2})
"\2" is ([\W])

is it right?


 
I take it you want words with ADJACENT letters the same.
You must be very careful to describe EXACTLY what you want.
If so, change the /\b(\w*(\w)\w*\2\w*)\b/ to /\b(\w*(\w)\2\w*)\b/

Yes, your description of \1 and \2 are correct.
That regex will only match digits though and could match all sorts of thing between the numbers.

Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top