1

Im trying to replace part of a String based on a certain phrase being present within it. Consider the string "Hello my Dg6Us9k. I am alive.".

I want to search for the phase "my" and remove 8 characters to the right, which removes the hash code. This gives the string "Hello. I am alive." How can i do this in Java?

0

5 Answers 5

5

You could achieve this through string.replaceAll function.

string.replaceAll("\\bmy.{8}", "");

Add \\b if necessary. \\b called word boundary which matches between a word character and a non-word character. .{8} matches exactly the following 8 characters.

To remove also the space before my

System.out.println("Hello my Dg6Us9k. I am alive.".replaceAll("\\smy.{8}", ""));
Sign up to request clarification or add additional context in comments.

3 Comments

What do you mean with 'add \\b if necessary'? What does it do?
@TheLostMind edited according to his expexted output but he says I want to search for the phase "my" and remove 8 characters to the right`
@AvinashRaj - ya.. but once I ran the program, his expected output differes from his question :)
2

This should do it:

String s = ("Hello my Dg6Us9k. I am alive");
s.replace(s.substring(s.indexOf("my"), s.indexOf("my")+11),"");

That is replacing the string starts at "my" and is 11 char long with nothing.

Comments

1

Use regex like this :

public static void main(String[] args) {
    String s = "Hello my Dg6Us9k. I am alive";
    String newString=s.replaceFirst("\\smy\\s\\w{7}", "");
    System.out.println(newString);
}

O/P : Hello. I am alive

3 Comments

The w before brackets means it will search a word? 7 is maximum length or required length?
@Kahler - exact 7. w can match a-zA-Z_
This works pretty well, thanks for the suggestion! However it does need to be passed to a string first before it displays the amended string.
1

Java strings are immutable, so you cannot change the string. You have to create a new string. So, find the index i of "my". Then concatenate the substring before (0...i) and after (i+8...).

int i = s.indexOf("my");
if (i == -1) { /* no "my" in there! */ }
string ret = s.substring(0,i);
ret.concat(s.substring(i+2+8));
return ret;

Comments

0

If you want to be flexible about the hash code length, use the folowing regexp:

String foo="Hello my Dg6Us9k. I am alive.";
String bar = foo.replaceFirst("\\smy.*?\\.", ".");
System.out.println(bar);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.