-1

Is there way to get max index parameter for pattern of the MessageFormat object? for example:

  1. "Dear {0}, some text {0} text" -> 1
  2. "Dear {0}, some text {1} text" -> 2
  3. "{0,choice,0#0 User|1#User|1<{1} Users}" -> 2
user1820916
  • 159
  • 10
  • [Very similar question and possible suitable answer](https://stackoverflow.com/questions/4989106/string-format-count-the-number-of-expected-args). Basically, use a regex on the string before passing it to the MessageFormat – Draken Dec 20 '19 at 08:31
  • could you please help me to write regex with the same kind of expression? It you take a look deeper on your example, you may notice that it does not cover example 3. Thank you in advance. – user1820916 Dec 20 '19 at 08:49
  • Nope, not something I have the time for. Good luck – Draken Dec 20 '19 at 08:54
  • Are you sure the third one is correct? Shouldn' t is `"{0,choice,0#0 User|1#User|1<{0} Users}"`, is it? – Renato Dec 20 '19 at 10:23
  • yes, please take a look at the doc https://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html – user1820916 Dec 20 '19 at 11:17
  • Sure, but https://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html there is this row that is similar to yours, but different: more similar to mine: `form.applyPattern( "There {0,choice,0#are no files|1#is one file|1 – Renato Dec 20 '19 at 11:50
  • Sure but depend on condition (for different languages) result maybe different. You mean the end result, if I understand you right. If the first template was used , result is 1, if the second result is 2. I would like to know the max value before apply MessageFormat. I wrote only 3 examples but it would be nice to cover the whole format MessageFormat. My example relative simple. It maybe much more complex. I think regex will be very complex and it should be something simple. – user1820916 Dec 20 '19 at 11:56
  • 1
    if you want to know how many placeholder the message format has _before_ use it, I think you have no choice: regexp; otherwise if the messageformat is used elsewhere one time, you can use `new HashSet(Arrays.asList(messageFormat.getFormats())).size()` – Renato Dec 20 '19 at 12:00
  • yes, you are right. Or use getFormatsByArgumentIndex(). Thank you for right direction. – user1820916 Dec 20 '19 at 12:15

1 Answers1

0

If you used it once you can use:

 MessageFormat format = new MessageFormat("Hello {0}, {1}");
// here somewhere you use it
 System.out.println(String.format("Get max index -- %d", new HashSet(Arrays.asList(format.getFormats())).size()));

This prints:

Get max index -- 2

Renato
  • 2,077
  • 1
  • 11
  • 22
  • thank you, You are right, but for the same value format = new MessageFormat("Hello {0}, {0}"); it prints 2 also – user1820916 Dec 20 '19 at 12:33