Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
874 views
in Technique[技术] by (71.8m points)

regex - String replace in Java

I currently have a string which contains the characters A, B and C for example the string looks like

"A some other random stuff B C"

the other random stuff doesn't contain A, B or C I want to replace the A, B & C with 'A', 'B' and 'C' respectively what's the best way to do that currently I'm doing:

String.replace("A", "'A'").replace("B", "'B'").replace("C", "'C'")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

cletus' answer works fine if A, B and C are those exact single characters, but not if they could be longer strings and you just called them A, B and C for example purposes. If they are longer strings you need to do:

String input = "FOO some other random stuff BAR BAZ";
String output = input.replaceAll("FOO|BAR|BAZ", "'$0'");

You will also need to escape any special characters in FOO, BAR and BAZ so that they are not interpreted as special regular expression symbols.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...