1

I am reading in Strings from a file like...an example would be:

I JUMP UP HIGH IN THE AIR WITH SOUP TO GET TO YOU.

How would I do a conditional replaceAll, e.g. replace all P at end of word unless the word ends with UP.

This what I tried based on the example for U at the end of the word:

s = s.replaceAll("(!UP\\b)P\\b", "PS")

The above I would expect to change the string s to:

I JUMPS UP HIGH IN THE AIR WITH SOUP TO GET TO YOU.
1

1 Answer 1

0

Your expression is pretty close: all you need is to check that the prior character is not a U, rather than UP, because P is already being matched:

(?<!U)P\b

This matches a single character P at the word boundary, unless it is preceded by a U character.

Demo.

Sign up to request clarification or add additional context in comments.

4 Comments

What if I don't want to change if it ends with OUP?
@Hedgebox Then you use (?<!OU) - i.e. P unless preceded by OU.
Tks. Is there a good tutorial on string manipulation with examples you can point me to?
@Hedgebox I keep this tutorial handy - it discusses regular expressions in great details.

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.