0

I failed after several tries to make a regex to find if a string contains a placeholder like %1$s or %3$d in a message like:

Hello, %1$s! You have %2$d new messages.

Can somebody give me, any help ?

How can I count how many placeholders are there ?

Oliver
  • 24,606
  • 7
  • 65
  • 89
Buda Florin
  • 594
  • 2
  • 11
  • 27

3 Answers3

0

You can use this regex in String#matches method call:

".*?%\\d+\\$[sd].*"

Code:

boolean found = string.matches( ".*?%\\d+\\$[sd].*" );
anubhava
  • 713,503
  • 59
  • 514
  • 593
0

Try with this pattern:

Pattern.compile("^.*%[0-9]+\\$[sd].*");

To count all matches, you could use Matcher and count like this:

int count = 0;
while (matcher.find())
  count++;

I'm not sure there's a more efficient way.

nKn
  • 13,590
  • 9
  • 42
  • 59
0

This will capture both cases. If you are using Java, I've provided a link on how to count matches.

(%1\$s|%2\$d)

java-regex-match-count

Community
  • 1
  • 1
dthartman
  • 104
  • 1
  • 5
  • In lieu of changing my regex to look like the other posts, let me just say the other regex answers provided are good, since they are more generic. – dthartman Jan 27 '14 at 17:44