0

I am new to java but not programming in general. I've been trying to understand Java String replaceAll...specifically I am reading in Strings from a text file...an example would be "I JUMP UP HIGH IN THE AIR TO GET TO YOU."

1) I want to change "I" to "A" where I is not the beginning of a word, and 2) U to "O" where U is at the end of a word. Any help would be appreciated. (Also, if you can point me to a good tutorial on the topic [I learn best by looking at examples] that would be appreciated)

1

1 Answer 1

1

Try this.

String s = "I JUMP UP HIGH IN THE AIR TO GET TO YOU.";
s = s.replaceAll("(?!\\b)I", "A")
     .replaceAll("U\\b", "O");
System.out.println(s);
// -> I JUMP UP HAGH IN THE AAR TO GET TO YOO.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much...This was perfect. I have 2 more questions...How would I do a conditional replaceAll...i.e. replace all "P" at end of word unless "UP"...I looked at the tutorial shmosel provided the link to...but I didn't get it...I could really use a tutorial that shows examples if you know of one please provide the link to it....
This what I tried based on your example for "U" at the end of the word.....s = s.replaceAll("(!UP)P\\b", "PS")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.