Java string: replacing a string with multiple values

I am currently creating a configuration file that will replace this line with several variables, it is difficult for me to explain this, so it might be better to show you what I mean:

The following method will be used with String: Hello ~ and is welcomed in ~!

private static String REPLACE_CHAR = "~"; public static String parse(String key, String... inputs) { int cache = matchCache.get(key, -1); String value = customConfig.getString(key); if (cache == -1) { cache = StringUtils.countMatches(value, REPLACE_CHAR); matchCache.put(key, cache); } for (int i = 0; i < cache; i++) { value = value.replaceFirst(REPLACE_CHAR, inputs[i]); } return value; } 

what would be a quick way to replace ~ with the first input, then go to the second ~ and so on ...

Now the main reason I didn’t use another user's code: Ideally, I would like to create a list of various replaceable characters, which, in turn, will replace the variable automatically, so in this code I can not give it any inputs, but it will check a list for interchangeable characters and execute a method such as getYourName () Does this list need to be checked every time so that the template can still be compiled?

I do this to learn as much as for effectiveness, I lack the ability when it comes to regular expression!

+4
source share
1 answer

If you are looking for efficiency, you can create an instance of Matcher using a regular expression, and then use the find() method to search for occurrences by adding a replacement for each occurrence in StringBuffer .

 private Matcher matcher = Pattern.compile("([~])").matcher(""); public String parse(String key, String... inputs) { String value = customConfig.getString(key); matcher.reset(value); StringBuffer sb = new StringBuffer(); int i = 0; while (matcher.find()) { String text = matcher.group(1); matcher.appendReplacement(sb, inputs[i++]); } matcher.appendTail(sb); return sb.toString(); } System.out.println(parse("foo", "TFC", "James Bond")); // prints "Hello TFC, my name is James Bond" // if customConfig.getString("foo") returns "Hello ~, my name is ~" 

This way you avoid finding from the beginning of the string during every loop involved in String.replaceFirst . But you can still cache the number of found ~ if you want to check that the length of input[] is equal to it.

The above example ignores the fact that the correct number of entries is stored in inputs[] .

Runnable sample can be found here: http://ideone.com/QfE03a

+2
source

Source: https://habr.com/ru/post/1445633/


All Articles