0

here is my input string:
bar somthing foo bar somthing foo

I would like to count number of a character (ex: 't') between bar & foo
bar somthing foo -> 1
bar somthing foo -> 1

I know we can use
/bar(.*?)foo/
and then count number of character in matches[1] with a String function

Is there way to do this w/o string function to count?

tqwer
  • 103
  • 1
  • 2
  • 9

2 Answers2

1

A Perl solution:

$_ = 'bar test this thing foo';
my $count = /bar(.*?)foo/ && $1 =~ tr/t//;
print $count;

Output:

4

Just for fun, using a single expression with (?{ code }):

$_ = 'bar test this thing foo';

my $count = 0;
/bar ( (?:(?!bar)[^t])*+ ) (?:t (?{ ++$count; }) (?-1) )*+ foo/x or $count = 0;

print $count;
Qtax
  • 33,241
  • 9
  • 83
  • 121
0

@Qtax: the subject says PCRE... so it's not exactly perl. Hence (?{ code }) would most probably be unsupported (let alone the full perl code). Though both solutions are cool ;)

@tqwer: you can get the match and then replace [^t] with "" and check length.. though i am not sure what the logic behind counting with regex would be ;)

poncha
  • 7,726
  • 2
  • 34
  • 38