How to insert backslash into my string in java? - java

I have string, and I want to replace one of its character with backslash \
I tried the following, but no luck.
engData.replace("'t", "\\'t")
and
engData = engData.replace("'t", String.copyValueOf(new char[]{'\\', 't'}));
INPUT : "can't"
EXPECTED OUTPUT : "can\'t"
Any idea how to do this?

Try this..
String s = "can't";
s = s.replaceAll("'","\\\\'");
System.out.println(s);
out put :
can\'t
This will replace every ' occurences with \' in your string.

Try like this
engData.replace("'", "\\\'");
INPUT : can't
EXPECTED OUTPUT : can\'t

String is immutable in Java. You need to assign back the modified string to itself.
engData = engData.replace("'t", "\\'t"); // assign the modified string back.

This is possible with regex:
engData = engData.replaceAll("('t)","\\\\$1");
The ( and ) specify a group. The 't will match any string containing 't. Finally, the second part replaced such a string with a backslash character: \\\\ (four because this), and the first group: $1. Thus you are replacing any substring 't with \'t
The same thing is possible without regex, what you tried (see this for output):
engData = engData.replace("'t","\\'t"); //note the assignment; Strings are immutable
See String.replace(CharSequence, CharSequence)

For String instances you can use, str.replaceAll() will return a new String with the changes requested:
String str = "./";
String s_modified = s.replaceAll("\\./", "");

The following works for me:
class Foobar {
public static void main(String[] args) {
System.err.println("asd\\'t".replaceAll("\\'t", "\\\'t"));
}
}

Related

How to find and replace '[' in a String?

i am having a String "['MET', 'MISSED']". Here i want to replace "[ to [ and ]" to ]. I have used the escape sequences in my String like
wkJsonStr.replaceAll("\"\\[","[");
and
wkJsonStr.replaceAll("\\]\"","]");
but none of the above worked. In 'watch' i edited like
wkJsonStr.replaceAll("\"[","[");
and it worked. But in my Android Studio Editor this Expression is not allowed. I am getting "Unclosed character class".
I am expecting my String after replacing to be like ['MET', 'MISSED']. I want to remove the first and last quotation alone and i would like to achieve it by replaceAll method.
Remember that string are immutable in java...
just calling the replace method will take no effect, you need to assign the return value, otherwise will get lost.
Example:
public static void main(String[] args) {
String wkJsonStr = "\"['MET', 'MISSED']\"";
System.out.println(wkJsonStr);
wkJsonStr = wkJsonStr.replaceAll("\"\\[", "[").replaceAll("\\]\"", "]");
System.out.println(wkJsonStr);
}
this will print.
"['MET', 'MISSED']"
['MET', 'MISSED']
You can use replace instead of replaceAll, but if you really need to use replaceAll then you can do:
wkJsonStr.replaceAll("\"\\Q[\\E","[").replaceAll("\\Q]\\E\"","]")
Here,
\" literally denotes "
The part between \\Q and \\E is literally treated., i.e,
\\Q[\\E denotes [
\\Q]\\E denotes ]
I agree with #Wiktor Stribiżew's comment. And you should declare your String like this:
String str = "\"['MET', 'MISSED']\""; // like this your editor will not give an error
str = str.replace("\"[","[");
str = str.replace("]\"","]");
textview.setText(str);
I finally realized that the isssue is not with the Regex character. Its the Variable which i am using. when i am replacing one by one it is not forwarding the result to the next step. So i have assigned the value to a variable and now its working.
String firstResult = wkJsonStr.replaceAll("\"\\[","[");
and
String result = firstResult.replaceAll("\\]\"","]");
is working for me. Or This step will do a trick.
String result= wkJsonStr.replaceAll("\"\\[","[").replaceAll("\\]\"","]");

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

Java replaceAll method with a variable string and escaped dot

I'm having a hard time figuring this one out, so I ask for your help. Here's the deal:
String str = "02-EST-WHATEVER-099-00.dwg";
String newStr = str.replaceAll("([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)", "$1$2");
The block of code above results in 02-EST-WHATEVER-099-.dwg (removed the last "00", just before the extension). Great, that's what I need!
But the RegEx I use above has to be created on the fly (the field I'm removing can be in a different position). So I used some code to create the RegEx string (here's what the result would look like if I just declared it):
String regexRemoveRev = "([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)";
Now, if I out.print(regexRemoveRev), I get ([^-_\.]+-[^-_\.]+-[^-_\.]+-[^-_\.]+-)[^-_\.]+(\.[^-_\.]+) (notice the single backslashes).
And when i try the replaceAll again, it doesn't work:
String str = "02-EST-WHATEVER-099-00.dwg";
String newStr = str.replaceAll(regexRemoveRev, "$1$2");
So I thought it could be because of the single backslashes, and I tried declaring regexRemoveRev with 4 of them, instead of just 2:
String regexRemoveRev = "([^-_\\\\.]+-[^-_\\\\.]+-[^-_\\\\.]+-[^-_\\\\.]+-)[^-_\\\\.]+(\\\\.[^-_\\\\.]+)";
The output of out.print(regexRemoveRev) is the double backslash version of the RegEx, as expected:
([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)
But the replace still doesn't work!
How do I get this to do what I want?
I have just wrote a short program and in both cases it works here it is:
public class StringTest
{
public static void main(String[] args)
{
String str = "02-EST-WHATEVER-099-00.dwg";
String newStr = str.replaceAll("([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)", "$1$2");
String regexRemoveRev = "([^-_\\.]+-[^-_\\.]+-[^-_\\.]+-[^-_\\.]+-)[^-_\\.]+(\\.[^-_\\.]+)";
String newStr1 = str.replaceAll(regexRemoveRev, "$1$2");
System.out.println("newStr: "+newStr);
System.out.println("regexRemoveRev: "+regexRemoveRev);
System.out.println("newStr: "+newStr1);
}
}
The out put from the above:
newStr: 02-EST-WHATEVER-099-.dwg
regexRemoveRev: ([^-.]+-[^-.]+-[^-.]+-[^-.]+-)[^-.]+(.[^-.]+)
newStr: 02-EST-WHATEVER-099-.dwg
I am not sure why is not working for you!! or is it something else you are asking and I got wrong

How to use replace(char, char) to replace all instances of character b with nothing

How do i use replace(char, char) to replace all instances of character "b" with nothing.
For example:
Hambbburger to Hamurger
EDIT: Constraint is only JDK 1.4.2, meaning no overloaded version of replace!
There's also a replaceAll function that uses strings, note however that it evals them as regexes, but for replacing a single char will do just fine.
Here's an example:
String meal = "Hambbburger";
String replaced = meal.replaceAll("b","");
Note that the replaced variable is necessary since replaceAll doesn't change the string in place but creates a new one with the replacement (String is immutable in java).
If the character you want to replace has a different meaning in a regex (e.g. the . char will match any char, not a dot) you'll need to quote the first parameter like this:
String meal = "Ham.bur.ger";
String replaced = meal.replaceAll(Pattern.quote("."),"");
Strings are immutable, so make sure you assign the result to a string.
String str = "Hambbburger";
str = str.replace("b", "");
You don't need replaceAll if you use Java 6. See here: replace
Try this code....
public class main {
public static void main(String args[]){
String g="Hambbburger.i want to eat Hambbburger. ";
System.out.print(g);
g=g.replaceAll("b", "");
System.out.print("---------After Replacement-----\n");
System.out.print(g);
}
}
output
Hambbburger.i want to eat Hambbburger. ---------After Replacement-----
Hamurger.i want to eat Hamurger.
String text = "Hambbburger";
text = text.replace('b', '\0');
The '\0' represents NUL in ASCII code.
replaceAll in String doesnot work properly .It's Always recomend to use replace()
Ex:-
String s="abcdefabcdef";
s=s.replace("a","");
String str="aabbcc";
int n=str.length();
char ch[]=str.toCharArray();
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(ch[i]==ch[j])
{
ch[j]='*';
}
}
}
String temp=new String(ch);
for(int i=0;i<temp.length();i++)
{
if(temp.charAt(i)!='*')
System.out.print(temp.charAt(i));
}

Use String.split() with multiple delimiters

I need to split a string base on delimiter - and .. Below are my desired output.
AA.BB-CC-DD.zip ->
AA
BB
CC
DD
zip
but my following code does not work.
private void getId(String pdfName){
String[]tokens = pdfName.split("-\\.");
}
I think you need to include the regex OR operator:
String[]tokens = pdfName.split("-|\\.");
What you have will match:
[DASH followed by DOT together] -.
not
[DASH or DOT any of them] - or .
Try this regex "[-.]+". The + after treats consecutive delimiter chars as one. Remove plus if you do not want this.
You can use the regex "\W".This matches any non-word character.The required line would be:
String[] tokens=pdfName.split("\\W");
The string you give split is the string form of a regular expression, so:
private void getId(String pdfName){
String[]tokens = pdfName.split("[\\-.]");
}
That means to split on any character in the [] (we have to escape - with a backslash because it's special inside []; and of course we have to escape the backslash because this is a string). (Conversely, . is normally special but isn't special inside [].)
Using Guava you could do this:
Iterable<String> tokens = Splitter.on(CharMatcher.anyOf("-.")).split(pdfName);
For two char sequence as delimeters "AND" and "OR" this should be worked. Don't forget to trim while using.
String text ="ISTANBUL AND NEW YORK AND PARIS OR TOKYO AND MOSCOW";
String[] cities = text.split("AND|OR");
Result : cities = {"ISTANBUL ", " NEW YORK ", " PARIS ", " TOKYO ", " MOSCOW"}
pdfName.split("[.-]+");
[.-] -> any one of the . or - can be used as delimiter
+ sign signifies that if the aforementioned delimiters occur consecutively we should treat it as one.
I'd use Apache Commons:
import org.apache.commons.lang3.StringUtils;
private void getId(String pdfName){
String[] tokens = StringUtils.split(pdfName, "-.");
}
It'll split on any of the specified separators, as opposed to StringUtils.splitByWholeSeparator(str, separator) which uses the complete string as a separator
String[] token=s.split("[.-]");
It's better to use something like this:
s.split("[\\s\\-\\.\\'\\?\\,\\_\\#]+");
Have added a few other characters as sample. This is the safest way to use, because the way . and ' is treated.
Try this code:
var string = 'AA.BB-CC-DD.zip';
array = string.split(/[,.]/);
You may also specified regular expression as argument in split() method ..see below example....
private void getId(String pdfName){
String[]tokens = pdfName.split("-|\\.");
}
s.trim().split("[\\W]+")
should work.
you can try this way as split accepts varargs so we can pass multiple parameters as delimeters
String[]tokens = pdfName.split("-",".");
you can pass as many parameters that you want.
If you know the sting will always be in the same format, first split the string based on . and store the string at the first index in a variable. Then split the string in the second index based on - and store indexes 0, 1 and 2. Finally, split index 2 of the previous array based on . and you should have obtained all of the relevant fields.
Refer to the following snippet:
String[] tmp = pdfName.split(".");
String val1 = tmp[0];
tmp = tmp[1].split("-");
String val2 = tmp[0];
...

Categories