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
Related
I'm trying to create a method which can highlight text in a jlabel according user entered search text. it works fine except it case sensitive. I used a regex (?i) to ignore case. But still it case sensitive.
private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {
String SourceText = "this is a sample text";
String SearchText = jTextField1.getText();
if (SourceText.contains(SearchText)) {
String OutPut = "<html>" + SourceText.replaceFirst("(?i)" + SearchText, "<span style=\"background-color: #d5f4e6;\">" + SearchText + "</span>") + "</html>";
jLabel1.setText(OutPut);
} else {
jLabel1.setText(SourceText);
}
}
How can i fix this.
Update
contains is case sensitive.
How to check if a String contains another String in a case insensitive manner in Java
You have not used the matched text in the replacement, you hard-coded the same string you used in the search. Since you wrap the whole match with html tags, you need to use the $0 backreference in the replacement (it refers to the whole match that resides in Group 0).
Besides, you have not escaped ("quoted") the search term, it may cause trouble if the SearchText contains special regex metacharacters.
You can fix the code using
String OutPut = "<html>" + SourceText.replaceFirst("(?i)" + Pattern.quote(SearchText), "<span style=\"background-color: #d5f4e6;\">$0</span>") + "</html>";
I have a string output which I need to match and I am using a regex
String schemaName = "Amazon";
String test = "{\"data\": [], \"name\": \"Amazon\", \"title\": \"StoreDataConfig\"}";
String output= method("\\[\\]",schemaName);
Matcher n = Pattern.compile(output).matcher(test);
boolean available = n.find();
System.out.println(available);
I wanted to validate the same and passing the regex to a method as mentioned
private static String method(String data, String schemaName) throws IOException {
System.out.println(data);
return ("{\"data\": " + data + ", \"name\": " + "\"" + schemaName + "\"" + ", \"title\": \"StoreDataConfig\"}");
}
But I am always getting java.util.regex.PatternSyntaxException: Illegal repetition.
Can you let me know what is the mistake?
If I don't use a method for [] and just giving it directly, I am not getting an error
It looks like you are doing this:
Take a valid regex for matching [].
Embed the regex in some JSON
Attempt to compile the JSON-with-an-embedded-regex as if the whole lot was a valid regex.
That fails ... because the JSON-with-an-embedded-regex is not a valid regex.
For a start, the { character is a regex meta character.
But the real puzzle is .... what are you actually trying to do here?
If you simply want a regex that matches a literal string then this will do it.
Pattern p = Pattern.compile(Pattern.quote(someLiteralString)).
And you could build a regex out of sub-regexes and literal strings by using Pattern.quote to escape the literal parts and then concatenating.
If what you are ultimately trying to do here is to extract information from a JSON string using pattern matching / regexes, then ... don't. The better approach is to use a proper JSON parser, and extract the information you need from the JSON object tree.
It's because you need to escape {} characters like this "\\{"
I have a string like this :
My word is "I am busy" message
Now when I assign this string to a pojo field, I get is escaped as below :
String test = "My word is \"I am busy\" message";
I have some other data in which I want something to be replaced by above string :
Let say my base string is :
String s = "There is some __data to be replaced here";
Now I when I use replaceAll :
String s1 = s.replaceAll("__data", test);
System.out.println(s1);
This returns me the output as :
There is some My word is "I am busy" message to be replaced here
Why that "\" is not appearing in after I replace. Do I need to escape it 2 times?
Also when use it like this :
String test = "My word is \\\"I am busy\\\" message";
then also it gives the same output as :
There is some My word is "I am busy" message to be replaced here
My expected output is :
There is some My word is \"I am busy\" message to be replaced here
Try this:
String test = "My word is \\\\\"I am busy\\\\\" message";
String s = "There is some __data to be replaced here";
System.out.println(s.replaceAll("__data", test));
To get the \ in your output you need to use \\\\\
From the docs:
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; see Matcher.replaceAll. Use
Matcher.quoteReplacement(java.lang.String) to suppress the special
meaning of these characters, if desired.
So you can use Matcher.quoteReplacement(java.lang.String)
String test = "My word is \"I am busy\" message";
String s = "There is some __data to be replaced here";
System.out.println(s.replaceAll("__data", test), Matcher.quoteReplacement(test));
You need to use four backslashes to print a single backslash.
String test = "My word is \\\\\"I am busy\\\\\" message";
String s = "There is some __data to be replaced here";
System.out.println(s.replaceAll("__data", test));
OR
String test = "My word is \"I am busy\" message";
String s = "There is some __data to be replaced here";
System.out.println(s.replaceAll("__data", test.replace("\"", "\\\\\"")));
Output:
There is some My word is \"I am busy\" message to be replaced here
I am using the code in Java:
String word = "hithere";
String str = "123hithere12345hi";
output(str.replaceAll("(?!"+word+")", "x"));
However, rather than outputting: xxxhitherexxxxxxx like I want it to, it outputs: x1x2x3hxixtxhxexrxex1x2x3x4x5xhxix x, I've tried a load of different regex patterns to try to do this, but I can't seem to figure out how to do this :(
Any help would be much appreciated.
Well this technically works. Using only replace all and only one line, and it's assuming you string does not contain a deprecated ASCII character (BEL)
String string = "hithere";
String string2 = "asdfasdfasdfasdfhithereasasdf";
System.out.println(string2.replaceAll(string,"" + (char)string.length()).replaceAll("[^" + (char)string.length() + "]", "x").replaceAll("" + (char)string.length(), string));
I think this is what you're looking for, if I'm not mistaken:
String pattern = "(\\d)|(hi$)";
System.out.println("123hithere12345hi".replaceAll(pattern, "X"));
The pattern replaces any numeric digits and the word "hi".
This lookaround based code will work for you:
String word = "hithere";
String string = "123hithere12345hi";
System.out.println(string.replaceAll(
".(?=.*?\\Q" + word + "\\E)|(?<=\\Q" + word + "\\E(.){0,99}).", "x"));
//=> xxxhitherexxxxxxx
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