2
votes

I'm looking for a way to take sed replacement expressions, such as s/hello/world/ (meaning replace all instances of 'hello' with 'world'), and apply them to a Java String. Ideally I would like to have support for other sed features like capture groups and so on, but they're not strictly necessary.

Are there any good libraries for this kind of thing in Java?


I could try to parse the sed expression myself, but I'd rather not get into the rats nest of escape handling.

2
the solution provided works for you? If so please accept it, or try to better explain in what way is defective. Thank you!Giuseppe Ricupero

2 Answers

6
votes

In Java what you need is accomplished with replaceAll() method, provided as built in in the String class:

public String replaceAll(String regex,String replacement)

Documentation

Example:

String test1 = "hello world";
System.out.println(test1.replaceAll("hello","hi"));
//Output: "hi world"

Capturing groups in replaceAll:

String test2 = "invert:me";
System.out.println(test2.replaceAll("(.*):(.*)","$2:$1"))
//Output: "me:invert"

NB

  • replaceAll() works as a sed substitution operation with global /g modifier.
  • replaceFirst() works exactly as the method above without the global modifier (replace only the first occurrence)
  • replace() is different. It does not accept any regex only literal string!
4
votes

Probably you are looking for this library:

unix4j

It is not actively developed since 2013, but otherwise it fits your needs. It allows you to write this:

cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort 

into this:

Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();