Please have a look at the below code
public class PuctuationRemover {
public PuctuationRemover()
{
String str = ":The red; third.fox is hungry!!! but, is he angry? doesn't! (yeah!). Call 911! system. can't access it! what the , hell . is this. people of my country, really? 123465 can^be,found.... OK . you got it? ";
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str);
System.out.println(str2);
}
public static void main(String[]args)
{
new PuctuationRemover();
}
}
The expected output is
The red thirdfox is hungry but is he angry doesn't yeah Call system can't access it what the hell is this people of my country really canbefound OK you got it
The output I get is
:The red; third.fox is hungry!!! but, is he angry? doesn't! (yeah!). Call 911! system. can't access it! what the , hell . is this. people of my country, ..............
The original working regex is here.
What has gone wrong here?
If you need to remove the punctuation, supply an empty string as the second argument instead of the original string itself. The second argument to replaceAll is not the original string, but what to replace the match with. Change
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str);
with
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", "");
Use String str2 = str.replaceAll("[^a-zA-Z'\\s]+", "");
You are doing String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str); .You are replacing the whole original String.
Please see this javadoc for more on String replaceAll.
Here in public String replaceAll(String regex, String replacement) second argument, i.e replacement is the string to be substituted for each match.
Note: Its better to catch PatternSyntaxException .
You're replacing your old string with your old string, which means you keep the same string even after replacing it. What you need to do is replace all of the characters specified in the regex with a no-character "".
EDIT: Darn, you people are fast typers! =P
Related
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("\\]\"","]");
So, I'm trying to parse a String input in Java that contains (opening) square brackets. I have str.replace("\\[", ""), but this does absolutely nothing. I've tried replaceAll also, with more than one different regex, but the output is always unchanged. Part of me wonders if this is possibly caused by the fact that all my back-slash characters appear as yen symbols (ever since I added Japanese to my languages), but it's been that way for over a year and hasn't caused me any issues like this before.
Any idea what I might be doing wrong here?
Strings are immutable in Java. Make sure you re-assign the return value to the same String variable:
str = str.replaceAll("\\[", "");
For the normal replace method, you don't need to escape the bracket:
str = str.replace("[", "");
public String replaceAll(String regex, String replacement)
As shown in the code above, replaceAll method expects first argument as regular expression and hence you need to escape characters like "(", ")" etc (with "\") if these exists in your replacement text which is to be replaced out of the string. For example :
String oldString = "This is (stringTobeReplaced) with brackets.";
String newString = oldString.replaceAll("\\(stringTobeReplaced\\)", "");
System.out.println(newString); // will output "This is with brackets."
Another way of doing this is to use Pattern.quote("str") :
String newString = oldString.replaceAll(Pattern.quote("(stringTobeReplaced)"), "");
This will consider the string as literal to be replaced.
As always, the problem is not that "xxx doesn't work", it is that you don't know how to use it.
First things first:
a String is immutable; if you read the javadoc of .replace() and .replaceAll(), you will see that both specify that a new String instance is returned;
replace() accepts a string literal as its first argument, not a regex literal.
Which means that you probably meant to do:
str = str.replace("[", "");
If you only ever do:
str.replace("[", "");
then the new instance will be created but you ignore it...
In addition, and this is a common trap with String (the other being that .matches() is misnamed), in spite of their respective names, .replace() does replace all occurrences of its first argument with its second argument; the only difference is that .replaceAll() accepts a regex as a first argument, and a "regex aware" expression as its second argument; for more details, see the javadoc of Matcher's .replaceAll().
For it to work it has to be inside a method.
for example:
public class AnyClass {
String str = "gtrg4\r\n" + "grtgy\r\n" + "grtht\r\n" + "htrjt\r\n" + "jtyjr\r\n" + "kytht";
public String getStringModified() {
str.replaceAll("\r\n", "");
return str;
}
}
If i want to replace one string variable with exact string in java, what can I do?
I know that replace in java , replace one exact string with another, but now i have string variable and i want to replace it's content with another exact string.
for example:
`String str="abcd";
String rep="cd";`
Now I want to replace rep content with"kj"
It means that I want to have str="abkj" at last.
If I understand your question, you could use String.replace(CharSequence, CharSequence) like
String str="abcd";
String rep="cd";
String nv = "kj";
str = str.replace(rep, nv); // <-- old, new
System.out.println(str);
Output is (the requested)
abkj
i think he wants:
String toReplace = "REPLACE_ME";
"REPLACE_ME What a nice day!".replace(toReplace,"");
"REPLACEME What a nice day!".replace(toReplace,"") results in:
" What a nice day!"
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"));
}
}
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