-
regular expressions
I'm writing a program that modifies a string by capitalizing substrings between <upcase> </upcase> tags and removes tags, using regular expressions. How does capitalising itself work? I'm so far here
Code:
public class string3 {
public static void main(String[] args) {
String str = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
System.out.println(str);
String replacedStr = str.replaceAll("(<upcase>)(.*?)(</upcase>)", "$2");
System.out.println(replacedStr);
}
}
...but I can't get the substrings in caps.
-
something like:
Code:
//keep in mind this array is only of size 2 so if you have more words between uppercase you need to use bigger array
String brokenup[] = new String[2];
//break the two words between uppercase into individual words
brokenup = replacedStr.split(" ");
//get the first letter of the first word and capitalize it
String firstWordFirstLetter = brokenup[0].chartAt(0).toUpperCase();
//create the first word by combining the capitalized first letter with rest of the word
String firstWord = firstWordFirstLetter + borkenup[0].substring(1,brokenup[0].length -1);
//basically this does same as what we did for above word
String secWordFirstLetter = brokenup[1].charAt(0).toUpperCase();
String secWord = secWordFirstLetter + brokenup[1].substring(1,brokenup[1].length-1);
System.out.println(firstWord+" "+secWord);
this is a rough idea of how it should work. Didn't test this so might have to correct errors but this gives you an idea. This is not the most simplest way nor shortest code to do this i am sure it is possible to do this without creating so many vars and statements.
-
Thanks! I was thinking if there was some regex operator for the replacing expression, something like "\\U" which I found somewhere on the net but it doesn't seem to work. Or maybe someway to use the toUpperCase() method on the replacing part, so that the whole thing goes with a few lines.
-