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
  • 27,510
  • 9
  • 72
  • 103
Buda Florin
  • 624
  • 2
  • 12
  • 30

3 Answers3

0

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

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

Code:

boolean found = string.matches( ".*?%\\d+\\$[sd].*" );
anubhava
  • 761,203
  • 64
  • 569
  • 643
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,691
  • 9
  • 45
  • 62
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