Using replaceAll() is giving me a rexex exception.
This is the code I am using:
public class test {
public static void main(String[] args) {
String text= "This is to be replaced &1 ";
text = text.replaceAll("&1", "&");
System.out.println(text);
}
}
EXCEPTION:
Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference
at java.util.regex.Matcher.appendReplacement(Unknown Source)
at java.util.regex.Matcher.replaceAll(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at test.main(test.java:7)
Seems to work fine for me. http://ideone.com/7qR6Z
But for something this simple, you can avoid regex and just use string.replace()
text = text.replace("&1", "&");
If you don't want regex then use String#replace method instead like this:
"This is to be replaced &1 ".replace("&1", "&")
My solution for this error while replacing with "$" sign was to replace all "$" with "\\$" like in code bellow:
myString.replaceAll("\\$", "\\\\\\$");
You can use Pattern.quote() to compile any string into a regular expression. Try:
public class test {
public static void main(String[] args) {
String text= "This is to be replaced &1 ";
text = text.replaceAll(Pattern.quote("&1"), "&");
System.out.println(text);
}
}
As it stands, your code works fine. However, if you mistyped or something and actually have
text = text.replaceAll("&1", "$");
Then you DO have to escape the replacement:
text = text.replaceAll("&1", "\\$");
Your question title shows how do i replace any string with a “$ ” in java? but your question text says String text= "This is to be replaced &1 "
If you're actually trying to replace a dollar sign, this is a special character in regular expressions, you need to escape it with a backslash. You need to escape that backslash, because blackslash is a special character in Java, so assuming dollar sign is what you intended:
String text = "This is to be replaced $1 ";
text = text.replaceAll("\\$1", "\\$");
System.out.println(text);
EDIT: Clarify some text
Related
I am using the wikimedia api to get content from wikipedia pages. The api returns a lot of "\n" as plain text. I want to remove them from a string
s = s.replaceAll("\\n", "");
s = s.replaceAll("\n", "");
Neither of these work, any ideas?
When your String contains a plaintext \n it is actually a \\n otherwise it would be displayed as a linebreak, which is why I found s = s.replaceAll("\\\\n","") to be working for me. An example snippet:
class Main{
public static void main(String[] args){
String s = "Hello\\nHello";
System.out.println(s);
s = s.replaceAll("\\\\n","");
System.out.println(s);
}
}
Remember that replaceAll takes a Regex: Since you want to replace 2 /s you have to escape both of them, therefore////
Hi Please to use below code format:
s= s.replace("\n", "").replace("\r", "");
Thanks
You can use the code below:
s = s.replace("\n", "");
but, the newline character can be different among the environments.
So, you can use this
s = s.replace(System.getProperty("line.separator"), "");
I've tried different way but not working yet.
public String SuEscapeHTML(String text){
text=text.replaceAll("/&/g", "&");
// and how to deal with the double quote? text=text.replaceAll("/"/g", """);
text=text.replaceAll("/'/g", "'");
text=text.replaceAll("/</g", "<");
text=text.replaceAll("/>/g", ">");
text=text.replaceAll("/\\/g", "\");
System.out.println(text);
return text;
}
nothing change by using this function.
So How to make it working?
The syntax of regex you are using is of JavaScript. This is how you will do it in Java
String text = "&>\"<\\'"; //You need to escape " in text also
System.out.println(text.replaceAll("&", "&"));
System.out.println(text.replaceAll("\"", """)); //For quotes
System.out.println(text.replaceAll("'", "'"));
System.out.println(text.replaceAll("<", "<"));
System.out.println(text.replaceAll(">", ">"));
System.out.println(text.replaceAll("\\\\", "\"));
Ideone Demo
I want to convert a string to get tab delimited format. In my opinion option 1 should do it. But it looks like option 2 is actually producing the desired result. Can someone explain why?
public class test {
public static void main(String[] args) {
String temp2 = "My name\" is something";
System.out.println(temp2);
System.out.println( "\"" + temp2.replaceAll("\"", "\\\"") +"\""); //option 1
System.out.println( "\"" + temp2.replaceAll("\"", "\\\\\"") +"\""); //option 2
if(temp2.contains("\"")) {
System.out.println("Identified");
}
}
}
and the output is:
My name" is something
"My name" is something"
"My name\" is something"
Identified
If you want an Excel compatible CSV format, the escaping of the double quote is two double quotes, so called self-escaping.
String twoColumns = "\"a nice text\"\t\"with a \"\"quote\"\".";
String s = "Some \"quoted\" text.";
String s2 = "\"" + s.replace("\"", "\"\"") + "\"";
And ... no head-ache counting the backslashes.
Use String#replace(CharSequence, CharSequence) instead of String#replaceAll(). The former is a simple string replacement, so it works as you'd expect if you haven't read any documentation or don't know about regular expressions. The latter interprets its arguments differently because it's a regex find-and-replace:
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string.
You'll get this output:
My name" is something
"My name\" is something"
"My name\\" is something"
Identified
I want split a string like this:
C:\Program\files\images\flower.jpg
but, using the following code:
String[] tokens = s.split("\\");
String image= tokens[4];
I obtain this error:
11-07 12:47:35.960: E/AndroidRuntime(6921): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:
try
String s="C:\\Program\\files\\images\\flower.jpg"
String[] tokens = s.split("\\\\");
In java(regex world) \ is a meta character. you should append with an extra \ or enclose it with \Q\E if you want to treat a meta character as a normal character.
below are some of the metacharacters
<([{\^-=$!|]})?*+.>
to treat any of the above listed characters as normal characters you either have to escape them with '\' or enclose them around \Q\E
like:
\\\\ or \\Q\\\\E
You need to split with \\\\, because the original string should have \\. Try it yourself with the following test case:
#Test
public void split(){
String s = "C:\\Program\\files\\images\\flower.jpg";
String[] tokens = s.split("\\\\");
String image= tokens[4];
assertEquals("flower.jpg",image);
}
There is 2 levels of interpreting the string, first the language parser makes it "\", and that's what the regex engine sees and it's invalid because it's an escape sequence without the character to escape.
So you need to use s.split("\\\\"), so that the regex engine sees \\, which in turn means a literal \.
If you are defining that string in a string literal, you must escape the backslashes there as well:
String s = "C:\\Program\\files\\images\\flower.jpg";
String[] tokens=s.split("\\\\");
Try this:
String s = "C:/Program/files/images/flower.jpg";
String[] tokens = s.split("/");
enter code hereString image= tokens[4];
Your original input text should be
C:\\Program\\files\\images\\flower.jpg
instead of
C:\Program\files\images\flower.jpg
This works,
public static void main(String[] args) {
String str = "C:\\Program\\files\\images\\flower.jpg";
str = str.replace("\\".toCharArray()[0], "/".toCharArray()[0]);
System.out.println(str);
String[] tokens = str.split("/");
System.out.println(tokens[4]);
}
Greetings all.
I am using the following regex to detect urls in a string
and wrap them inside the < a > tag
public static String detectUrls(String text) {
String newText = text
.replaceAll("(?:https?|ftps?|http?)://[\\w/%.-?&=]+",
"<a href='$0'>$0</a>").replaceAll(
"(www\\.)[\\w/%.-?&=]+", "<a href='http://$0'>$0</a>");
return newText;
}
i have a problem that the following links are not detected correctly:
i am not that good with regex, so please advise.
http://code.google.com/p/shindig-dnd/
http://confluence.atlassian.com/display/GADGETDEV/Gadgets+and+JIRA+Portlets
www.liferay.com/web/raymond.auge/blog/
(www.opensocial.org/)
http://www.google.com
I'm using this:
private static final String URL_REGEX =
"http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
Matcher matcher = URL_PATTERN.matcher(text);
text = matcher.replaceAll("$0");
return text;
The problem you have is that you are using - within a character group ([]) without escaping it, which is being used to define the range .-? (i.e. the characters ./0123456789:;<=>?). Either escape it \\- or put it at the end of the character class so that it doesn't complete a range.
public static String detectUrls(String text) {
String newText = text
.replaceAll("(?:https?|ftps?|http?)://[\\w/%.\\-?&=]+",
"<a href='$0'>$0</a>").replaceAll(
"(www\\.)[\\w/%.\\-?&=]+", "<a href='http://$0'>$0</a>");
return newText;
}
As marcog said, you should escape the - and to match the last 2 examples you gave, you have to make the http optionnal. Also http? matches htt wich is not a correct protocol.
So the regex will be:
"(?:(?:https?|ftps?)://)?[\\w/%.?&=-]+"