Regex to match say char 't' exactly once in a string and no more than once

G

Gancy

Some times Regex's which are supposed to be simple eats head. I have
come across one such, though looks very simple, i am frustrted to right
the expressions for it.

I want to match a specifice charecter in a string, say 't', exactly
once anywhere in the string, but should not match 't' more than once.
sounds simple is it not.
 
T

Tore Aursand

Gancy said:
I want to match a specifice charecter in a string, say 't', exactly
once anywhere in the string, but should not match 't' more than once.
sounds simple is it not.

What have you tried so far? Have you checked the Perl documentation,
especially the FAQ? Hint:

perldoc -q count
 
A

Anno Siegel

Tore Aursand said:
What have you tried so far? Have you checked the Perl documentation,
especially the FAQ? Hint:

perldoc -q count

That discusses counting of substrings, but not matching if there is
only one occurrence.

Now, in general it *is* the better solution to count and see if the
result is 1, especially if going for multi-character strings or even
general subpatterns.

For the problem of matching single occurrences of a *single character*,
there is a simple regex solution:

my $char = 't';
my $re = /
^ # beginning of string
[^$char]* # any number of characters different from $char
$char # a single $char
[^$char]* # any number of characters different from $char
$ # end of string
/x;

Anno
 
T

Tad McClellan

Gancy said:
I want to match a specifice charecter in a string, say 't', exactly
once anywhere in the string, but should not match 't' more than once.

/^[^t]*t[^t]*$/


sounds simple is it not.


Looks pretty simple to me...
 
R

Rasto Levrinc

Gancy said:
I want to match a specifice charecter in a string, say 't', exactly
once anywhere in the string, but should not match 't' more than once.
sounds simple is it not.

Here is funny way to do it without using regexp.

if (abs index($string, $char) == rindex($string, $char)) {
...
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top