How to replace part of a String in Java? - java

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?

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}", ""));

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.

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

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;

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);

Related

How to put new string between commas in original string

I have this original string and I want to insert new string between two dots of original string. I did it this way, but having errors.
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String new = originalString.replace(originalString.substring(originalString.indexOf(".") + 1), stringForReplace);
it gives me: "asdASfasdlpe.NewString"
Result should be: "asdASfasdlpe.NewString.asdasfdfepw"
I would do it like so.
from the question it looks like you want to replace the first occurrence so use replaceFirst
(?<=\\.) - look behind assertion - so start with following character
(?=\\.) - look ahead assertion - so end prior to that
.*? - reluctant quantifier to limit to just characters between two periods. Use * in case you have two adjacent periods since the string could be empty.
String s = "first.oldstring.third.fourth.fifth";
String n = "second";
s = s.replaceFirst("(?<=\\.).*?(?=\\.)",n);
System.out.println(s);
prints
first.second.third.fourth.fifth
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String a[]=originalString.split("[.]");
String newString="";
if(a.length==3) {
newString=originalString.replace(a[1], stringForReplace);
}
System.out.println(newString);
Or with ternary operator:
newString=(a.length== 3 ? originalString.replace(a[1], stringForReplace):null);
System.out.println(newString);
One shorter solution is to use regex with a lookahead and lookbehind
String replaced = originalString.replaceAll("(?<=\\.).+(?=\\.)", stringForReplace);
The problem with your code is due to using this particular piece of code:
originalString.substring(originalString.indexOf(".") + 1)
The reason is that indexof() function will only give the index on which "." was found on, and substring will only know where to start taking the substring from, but it wouldn't know where to end it.
Try this:
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String newString = originalString.replace(originalString.split("[.]", 3)[1], stringForReplace);
System.out.println(newString);
The split function in this piece of code will break the whole string by "."
and you will have the string you want to replace available to you.
originalString.split("[.]", 3)[1]
You could try the following:
public static void main(String[] args) {
String originalString ="asdASfasdlpe.hereNeedToPutNewString.asdasfdfepw";
String stringForReplace = "NewString";
String newStr = originalString.replaceAll("(?<=\\.).*(?=\\.)", stringForReplace);
//using lookahead and lookbehind regex
String newStr2 = originalString.replaceAll("\\..*\\.", "."+stringForReplace+".");
System.out.println(newStr);
System.out.println(newStr2);
}
One option uses lookahead and lookbehinds, you could opt to not use that if it is not supported.
Output:
asdASfasdlpe.NewString.asdasfdfepw
asdASfasdlpe.NewString.asdasfdfepw
Here You go:
String new = originalString.replace(originalString.substring(originalString.indexOf(".") + 1), stringForReplace)+originalString.substring(originalString.indexOf(".",originalString.indexOf(".")+1),originalString.length());
What I have done is adding the resultant string to the new String.indexOf function takes another argument too, which is the position the search will start

How to replace all numbers in java string

I have string like this String s="ram123",d="ram varma656887"
I want string like ram and ram varma so how to seperate string from combined string
I am trying using regex but it is not working
PersonName.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1))).replaceAll("[^0-9]+"));
The correct RegEx for selecting all numbers would be just [0-9], you can skip the +, since you use replaceAll.
However, your usage of replaceAll is wrong, it's defined as follows: replaceAll(String regex, String replacement). The correct code in your example would be: replaceAll("[0-9]", "").
You can use the following regex: \d for representing numbers. In the regex that you use, you have a ^ which will check for any characters other than the charset 0-9
String s="ram123";
System.out.println(s);
/* You don't need the + because you are using the replaceAll method */
s = s.replaceAll("\\d", ""); // or you can also use [0-9]
System.out.println(s);
To remove the numbers, following code will do the trick.
stringname.replaceAll("[0-9]","");
Please do as follows
String name = "ram varma656887";
name = name.replaceAll("[0-9]","");
System.out.println(name);//ram varma
alternatively you can do as
String name = "ram varma656887";
name = name.replaceAll("\\d","");
System.out.println(name);//ram varma
also something like given will work for you
String given = "ram varma656887";
String[] arr = given.split("\\d");
String data = new String();
for(String x : arr){
data = data+x;
}
System.out.println(data);//ram varma
i think you missed the second argument of replace all. You need to put a empty string as argument 2 instead of actually leaving it empty.
try
replaceAll(<your regexp>,"")
you can use Java - String replaceAll() Method.
This method replaces each substring of this string that matches the given regular expression with the given replacement.
Here is the syntax of this method:
public String replaceAll(String regex, String replacement)
Here is the detail of parameters:
regex -- the regular expression to which this string is to be matched.
replacement -- the string which would replace found expression.
Return Value:
This method returns the resulting String.
for your question use this
String s = "ram123", d = "ram varma656887";
System.out.println("s" + s.replaceAll("[0-9]", ""));
System.out.println("d" + d.replaceAll("[0-9]", ""));

How to get alphabets only from given albha-numberic word in java?

sorry for this if this is a silly question.but i need to know about this.
If i have a word like alphabets,numeric and special charters. I need to extract alphabets only.No need for numeric and special characters.I need to know is there default function is there in Java to split characters only?
eg.String word="te123##st";
I need test only.
This solution works with accentued/non-ascii caracters :
"te123##st\néàø_".replaceAll("[\\p{Digit}\\p{Punct}\\p{Space}]", "");
try this word.replaceAll("[^a-zA-Z]", "");
This will remove all non alphanumeric characters, but it will still remove accented characters.
String word = "te123##st";
word = word.replaceAll("[^\\p{Alpha}]", "");
// or word = word.replaceAll("[\\P{Alpha}]", "");
See apidoc reference.
try
word = word.replaceAll("\\P{Alpha}", "");
String word = "te123##st";
word = word.replaceAll("[\\W\\d._]", "");
try this:
word = word.replaceAll("[\\d##_]", "");
- I won't make this complicated using Regex, but will use inbuilt Java functionalities to answer this.
- First use subString() method to get the "abcd" part of the String, then use toCharArray() method to break the String into char elements, then use Character class's isDigit() method to know whether its a digit or not.
public class T1 {
public static void main(String[] args){
String s = "te123##st";
String str = s.substring(0,4);
System.out.println(str);
String tempStr = new String();
char[] cArr = str.toCharArray();
for(char a :cArr){
if(Character.isAlphabetic(a)){
System.out.println(a+" is a alphabet");
tempStr = tempStr + a;
}else{
System.out.println(a+" is not a alphabet");
}
}
System.out.println("The extracted String is: "+tempStr);
}
}

java - Why replaceAll is not working?

Im starting to learn regex and I don't know if I understand it correctly.
I have a problem with function replaceAll because it does not replace the character in a string that I want to replace.
Here is my code:
public class TestingRegex {
public static void main (String args[]) {
String string = "Hel%l&+++o_Wor_++l%d&#";
char specialCharacters[] = {'%', '%', '&', '_'};
for (char sc : specialCharacters) {
if (string.contains(sc + ""))
string = string.replaceAll(sc + "", "\\" + sc);
}
System.out.println("New String: " + string);
}
}
The output is the same as the original. Nothing changed.
I want the output to be : Hel\%l\&+++o\_Wor\_++l\%d\&\#.
Please help. Thanks in advance.
The reason why it's not working: You need four backslashes in a Java string to create a single "real" backslash.
string = string.replaceAll(sc, "\\\\" + sc);
should work. But this is not the right way to do it. You don't need a for loop at all:
String string = "Hel%l&+++o_Wor_++l%d&#";
string = string.replaceAll("[%&_]", "\\\\$0");
and you're done.
Explanation:
[%&_] matches any of the three characters you want to replace
$0 is the result of the match, so
"\\\\$0" means "a backslash plus whatever was matched by the regex".
Caveat: This solution is obviously not checking whether any of those characters had already been escaped previously. So
Hello\%
would become
Hello\\%
which you would not want to happen. Could this be a problem?

How to replace last dot in a string using a regular expression?

I'm trying to replace the last dot in a String using a regular expression.
Let's say I have the following String:
String string = "hello.world.how.are.you!";
I want to replace the last dot with an exclamation mark such that the result is:
"hello.world.how.are!you!"
I have tried various expressions using the method String.replaceAll(String, String) without any luck.
One way would be:
string = string.replaceAll("^(.*)\\.(.*)$","$1!$2");
Alternatively you can use negative lookahead as:
string = string.replaceAll("\\.(?!.*\\.)","!");
Regex in Action
Although you can use a regex, it's sometimes best to step back and just do it the old-fashioned way. I've always been of the belief that, if you can't think of a regex to do it in about two minutes, it's probably not suited to a regex solution.
No doubt get some wonderful regex answers here. Some of them may even be readable :-)
You can use lastIndexOf to get the last occurrence and substring to build a new string: This complete program shows how:
public class testprog {
public static String morph (String s) {
int pos = s.lastIndexOf(".");
if (pos >= 0)
return s.substring(0,pos) + "!" + s.substring(pos+1);
return s;
}
public static void main(String args[]) {
System.out.println (morph("hello.world.how.are.you!"));
System.out.println (morph("no dots in here"));
System.out.println (morph(". first"));
System.out.println (morph("last ."));
}
}
The output is:
hello.world.how.are!you!
no dots in here
! first
last !
The regex you need is \\.(?=[^.]*$). the ?= is a lookahead assertion
"hello.world.how.are.you!".replace("\\.(?=[^.]*$)", "!")
Try this:
string = string.replaceAll("[.]$", "");

Categories