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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Count characters in string 1

Status
Not open for further replies.

fagga

Programmer
Jun 26, 2002
28
DE
Hello,

I want to count underscores in a string. I already found a solution:
Code:
$underscore_count = ($string =~ tr/_//);

This works fine, but I would like to count only underscores which are not preceded by a backslash. So, for example, in the string "foo_bar_bar\_foo" $underscore_count would be 2.
I tried this:

Code:
$underscore_count = ($string =~ tr/[^\\]_//);

But the results are very strange. Underscores without backslash are counted correct, but if I have two '_' and one '\_' in the string, he counts 4.

So my question actually is: How can I match a string which is not preceded by another string?

Thanks in advance for any clues and sorry for my bad english.
 
How about:
[tt]
$string=~s/\\_//g;
$underscore_count=($string=~tr/_//);
[/tt]
Of course, this changes $string .

-----
$world=~s/war/peace/g;
 
Thank you very much for your answer but it doesn't help. It is important to count only the underscores with no backslash in front of it.

I'm writing a chat program and everything between two underscores is printed bold. But if the user supplies only one underscore the whole chat output would be printed bold. That's why I need to know if the count of underscores in one line is even or not. For example, if there are three underscores, I append one at the end of the line.

But I also want to make it possible to really print an underscore without any bold effect. To mark those real underscores, the user escapes it with a backslash. But now I have to count only the underscores which make bold text and not the escaped underscores. So I have to count only underscores which are not preceded by a backslash.

I hope I explained it understandable.
 
That code should do what you want. The first line removes all backslash/underscore combinations from the string, then the second line counts the remaining underscores.

-----
$world=~s/war/peace/g;
 
I'm very sorry. And it works great. Thank you very much again.
 
TIMTOWTDI in one line using a negative lookbehind (see perlre for details):
Code:
my $underscore_count = $string =~ s/(?<!\\)_//g;
 
This is even better. I'm impressed. Thank you even more for your help.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top