Regular expression in Perl
Hi
I am trying to write a regular expression in perl that will match the first letter / character of a string and the last letter / character of the string. I have this statement for my expression.
Code:
if ($string =~ m/(^([a-z]+\s*)+$)/)
I think this is not correct, because I know that the ^ is used to match the first part of the string while the $ sign is used to match the ending part of string. i am not sure about my code, still I am posting my code, please help me.
Code:
#!/usr/bin/perl
while ()
{
print "enter something: \n";
chomp ($string =<STDIN>);
if ($string =~ m/(^([a-z]+\s*)+$)/)
{
print "Found letter '$1' was found ", pos($text), " \n";
print "This string begins and ends with same character with \n";
last;
}
else
{
print "This string does not begin and end with the same character \n";
}
}
Re: Regular expression in Perl
Hello
Are you trying to test a given string starts and ends with the same character? I just want to be sure that I have understood your problem correctly. If this is the case, I have tried it in two way. Find out what the first letter is and insert it into a variable, then find out what the last letter is and put it into another variable. And then you have to compare the tow strings. In this case there is no need of a regular expression. In general you have to first extract the first and the last letters. then construct your regular expression dynamically. and finally do the match.
Re: Regular expression in Perl
Hi
Thanks for replying
I have used the following statement in my code.
Code:
if ($string =~ m/^(.+)+(.+)\1$/)
1) axxxxxbxxxxxa
This string begins and ends with same character with
2) If the end is near
This string does not begin and end with the same character
The problem is that it will only check one way, I need it to check both ways. Do you have any suggestions