简体   繁体   中英

Replace parts of a string in Java

I need to replace parts of a string by looking up the System properties.

For example, consider the string It was {var1} beauty killed {var2}

I need to parse the string, and replace all the words contained within the parenthesis by looking up their value in System properties. If System.getProperty() returns null, then simply replace with empty character. This is pretty straightforward when I know the variables well ahead. But the string that I need to parse is not defined ahead. I wouldn't know how many number of variables are in the string and what the variable names are. Assuming a simple, well formatted string (no nested parenthesis, open - close matches), what is the simplest or the most elegant way to parse through the string and replace all the character sequences that are enclosed in the parenthesis?

Only solution I could come up with is to traverse the string from the first character, note down the positions of the start and end positions of the parenthesis, replace the string between them, and then continue until reaching the end of the string. Is there simpler way to do this?

You can use the parentheses to break the initial string into substrings, and then replace every other substring.

String[] substituteValues = {"the", "str", "other", "another"};
int substituteValuesIndex = 0;

String test = "Here is {var1} string called {var2}";

// split the string up into substrings
test = test.replaceAll("\\}", "\\{");
String[] splitString = test.split("\\{");

// now sub in your values
for (int k=1; k < splitString.length; k = k+2) {
    splitString[k] = substituteValues[substituteValuesIndex];
    substituteValuesIndex++;
}

String result = "";
for (String s : splitString) {
    result = result + s;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM