/    Sign up×
Community /Pin to ProfileBookmark

how to find the number of tokens using regular expression?

Hello

Assuming I have a sentence like so:
“Hello %1, I %3 %4 five days day ago. %5 need to talk to %6 later”

The sentence has wild cards that can be used as placeholders for actual strings which will replace the tokens.
Such replacement can yield the sentence
“Hello [b]Jeff[/b], I [b]saw[/b] [b]you[/b] five days day ago. [b]I[/b] need to talk to [b]you[/b] later”
The sentence above has 6 such placeholders.

Here is my question:
Given such sentence, how can I tell how many wild cards it has?
Note that the number isn’t limited to 1-9 but theoretically be very high.

I tried to use split with regular expressions but I must be using the wrong regular expression (I am fairly new to them).

I would appreciate any help

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@DJsACOct 18.2004 — [code=php]
$sentence = "Hello %1, I %3 %4 five days day ago. %5 need to talk to %6 later";

$tokens = substr_count($sentence, "%");
echo "You have ".$tokens." tokens in this string.<br>";
[/code]


Easy as substr_count ?
Copy linkTweet thisAlerts:
@jasongrauthorOct 18.2004 — This isn't a sound solution.

Your solution will also return 1 for this string

"5% of the population is happy"

where in fact it has 0 tokens

the correct solution uses regular expressions:
[code=php]
$numTokens = preg_match_all('/%d/', $string, $outTokens);
[/code]
Copy linkTweet thisAlerts:
@DJsACOct 18.2004 — If you already know the answer, why did you ask? :rolleyes:

I also didn't say that it works in all possible places.

search for '<space>%<char(s)><space>' would also have worked.

sorry I tried to help <_<
Copy linkTweet thisAlerts:
@NogDogOct 18.2004 — Or perhaps even more precise:
[code=php]
$numTokens = preg_match_all('/\b%\d+\b/', $string);
[/code]

b = word boundary

d = any digit

+ = 1 or more occurences of preceding character
Copy linkTweet thisAlerts:
@jasongrauthorOct 18.2004 — I didn't know that answer when I posted the question.

Later when I saw your reponse, I remembered that I solved it and I decided to post my answer so that everyone else could benefit from it
×

Success!

Help @jasongr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...