简体   繁体   中英

Java String Manipulation Conditional replaceAll

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 , eg 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.

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.

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