1

I'm trying to apply multiple regex on a string. I'm not able to get a good understanding on something of this matter.

I have multiple strings which would under go this replacement:

String csvFile = "/Users/john/Documents/chartFolder/chart_test_1.csv"
String chartTitle = csvFile.replaceAll("_", " ");
chartTitle = chartTitle.replaceAll(".*/", "");
chartTitle = chartTitle.replaceAll("\\..*", "");

I'd like the output to be -

chart test 1

which I achieve, but I feel is not good coding due to the multiple lines of coding.

If someone could please explain if it can be done in 1 line and how they come up with the solution, without just posting the solution that would be great.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
kapedcl
  • 11
  • 1
  • you can group the 2nd and 3rd replacement, as you're replacing for the same thing. – Augusto Mar 13 '15 at 22:32
  • 1
    possible duplicate of [Java Replacing multiple different substring in a string at once (or in the most efficient way)](http://stackoverflow.com/questions/1326682/java-replacing-multiple-different-substring-in-a-string-at-once-or-in-the-most) – mkobit Mar 13 '15 at 22:32
  • There is nothing wrong with multiple lines of code. Clean, easy to read code is more maintainable than dense 'clever' (oh look what I did in one line) code. – Appak Mar 13 '15 at 22:39
  • For the 2nd replacement I'm taking all characters out before the / so the string becomes "chart_test_1.csv" and for the 3rd replacement I'm deleting all characters after the "." – kapedcl Mar 13 '15 at 22:40

3 Answers3

1

You can concatinate all the replace Statements:

String chartTitle = csvFile.replaceAll("_", " ").replaceAll(".*/", "").replaceAll("\\..*", "");
Jens
  • 67,715
  • 15
  • 98
  • 113
1

You can do it with one replace, like this:

String chartTitle = csvFile.replaceAll(".*/|_|\\..*", " ").trim();

This uses an *alternation" to match all three targets, then replace them all with a space, which leaves a space at either end, which are then removed using trim().

The main problem with your idea, for which there is no work around, is that replaceAll()'s replacement term can't vary depending on the match.

You may also be interested to know that replace() still replaces all occurrences, it just uses a plain text pattern (not a regex), so you could code

str.replace("_",  " ")

with equal effect

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

You can save yourself some .replaceAll by building a better regular expression (which targets several substrings to replace), but only if the replacement String remains the same.

In your example:

chartTitle = chartTitle.replaceAll(".*/", "");
chartTitle = chartTitle.replaceAll("\\..*", "");

Can be grouped as you replace matches with the same substring (here : ""). You can use the "or" operator to build a "grouped" regular expression.

Otherwise, you have to call this function several times.

DavidL
  • 1,120
  • 1
  • 15
  • 34