-3

I know when I use .replace I can replace a specified String for another string. For example:

String string = “hi fjrkfinnek”;

string.replace(“fjrkfinnek”, “”);

I know using this will replace that specified part of the string with a blank space in this example. However, is it possible to remove everything that’s not “hi” instead of referencing what I want to replace?

The output I would desire is to remove everything but Hi by saying Remove everything that’s not Hi if that can be done!

alwaysStuckJava
  • 359
  • 1
  • 3
  • 10

5 Answers5

0

Right now you are asking: howto remove all that is "not X" from

Xxyz

The simple answer is: when you already know that X is supposed to be the leftover, then well "X" should do.

And a bit more seriously: one could think of using regular expressions here - but they only allow you to match something. Not to match on "not something".

You could start with [^hi] - but this doesn't do what you hope for: it simply says: anything that doesn't contain h/i will match.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 1
    I think Regex could be used like `(.*)hi(.*)` and replace/remove both group if any (not perfect but this is the idea). But the result would be the same as `String res = s.contains("hi") ? "hi" : "";` – AxelH Nov 14 '17 at 11:49
0

Well there are of course methods to make this working. For example replace accepts regex which is capable of negating by using negative lookahead (How to negate specific word in regex?). Or you can manually traverse the input etc.


Solution

However there is a much more easy solution. If you want to delete everything which is not foo in your input

test foo bar 123 test

then the result can either be completely empty (if foo is not contained) or only foo (if it was contained). So simply check for your needle being present:

public String deleteAllExceptFirst(String input, String needle) {
    if (input.contains(needle)) {
        return needle;
    } else {
        return "";
    }
}

Multiple instances

Note that if you want to preserve multiple foo occurrences you need additional work. Just count how many times foo is contained and then print it concatenated:

public String deleteAllExcept(String input, String needle) {
    StringBuilder sb = new StringBuilder();

    // Find all occurrences
    Pattern needlePatt = Pattern.compile(needle);
    Matcher matcher = needlePatt.matcher(input);
    while (m.find()) {
        // Build the result
        sb.append(needle);
    }

    return sb.toString();
}

For the test input

test foo bar 123 test foo foo bar foo

this yields

foofoofoofoo
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • Your multiple solution could append the builder directly instead of counting first. And the first could be shorter with `return input.contains(needle) ? needle : "":` – AxelH Nov 14 '17 at 11:58
  • @alwaysStuckJava Glad that it helped. I edited the answer to include the **multiple instances** scenario. – Zabuzard Nov 14 '17 at 11:58
0

Given the String you provided you can split it into words using the split() function and then append only those parts that don't contain the "hi".

If you use java 8, you can do that with a filter:

String string = “hi fjrkfinnek”;
    Arrays.asList(string.split(" ")).stream()
                     .filter(s -> !s.equals("hi")).collect(Collectors.joining());

In the code above, I get each word as a String then I stream it and I apply a filter so that only those different than "hi" are allowed. Finally I just join back into a String.

javing
  • 12,307
  • 35
  • 138
  • 211
0

There is no such library. You can do this like:

 String replaceOthers(String required, String fullString) {
    String result = fullString;
    try (Scanner scanner = new Scanner(fullString)) {
        while (scanner.hasNext()) {
            String current = scanner.next();
            if (!current.equals(required)) {
                result = result.replace(current, "");
            }
        }
        return result;
    }
}
Tharun
  • 311
  • 2
  • 14
0

I think using regex we can do this..

string.replaceAll("[^hi]", "?")
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • This doesn't apply to **words** but just for **sets of characters**, it would leave words like `iiiihhihihiiii` unchanged. – Zabuzard Nov 14 '17 at 12:02