Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to do sed search & replace in Java efficiently

 
Jack Bush
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Java Gurus,

I am wondering whether there is a way to do string search and replace similar to sed instead of using the conventional method of examining every character line by line in Java. Let’s look at an example of what I am referring to.

The file IncorrectSport.txt is made up of the following strings:

Scoccer=Wimbleton
Tennis=World Cup




I have a need to make string search and replacement to a large number of small text files and is looking for a more efficient approach to getting it done.

There is no issue with writing a simple yet dull laborious text manipulation program in Java.

Thanks in advance,

Jack
 
Campbell Ritchie
Sheriff
Pie
Posts: 49789
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don’t the replacing methods in the String class provide what you require?
 
Tim Moores
Bartender
Posts: 2895
46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't forget "s/Scoccer/Soccer/g" afterwards
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jack Bush wrote:
I am wondering whether there is a way to do string search and replace similar to sed instead of using the conventional method of examining every character line by line in Java.


Sed examines every character just like what you would have to write in Java. That's the most efficient way to do it (and the only reasonable way that's applicable to the general case).

Java does have a regex facility in the core API, however (which also examines every character), so you don't have to write the comparison code yourself.
 
Jack Bush
Ranch Hand
Posts: 235
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeff,

>Java does have a regex facility in the core API, however (which also examines every character), so you don't have to write the comparison code yourself.

What is the name of this class where can I find it?

Thank you to all for your suggestion but the latter one from Jeff appears to be the one I am looking for.

Jack
 
Maneesh Godbole
Saloon Keeper
Posts: 11092
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic