How to escape backslash in Java [duplicate] - java

This question already has an answer here:
regex: How to escape backslashes and special characters?
(1 answer)
Closed 8 years ago.
I was trying to escape a Json string as an input via Scanner and print to console,
i was not able to escape " \ " by replacing it with " \\ ",
I'm getting PatternSyntaxException
Here is my code
Scanner s = new Scanner(System.in);
String str = s.next();
String s3 = "";
if (str.contains("\\")) {
s3 = str.replaceAll("\\", "\\\\");
System.out.println(s3);
}
Here is my input to scanner
{"name":"nokia"}\
Help me please !

If you are using regex you have to use 4 backslashes \\\\ to parse the backslash as a literal.
So use s3 = str.replaceAll("\\\\", someOtherString);

Related

Using backslash (\) inside a String variable in java [duplicate]

This question already has answers here:
What is the backslash character (\\)?
(6 answers)
Closed last year.
I am not able to get the message value in the desired format.
String url = "sample"
String message ="/test{\"url\":"' + url + '\"}
The desired value of message is "/test{\"url\":\"sample\"}"
Any idea on this?
Try with this:
String url = "sample";
String message ="/test{\\\"url\\\":\""+url+"\\\"}";
Or you can use String.format:
String url = "sample";
String message = String.format("/test{\\\"url\\\":\"%s\\\"}",url);
Try the following syntax:
String url = "sample";
String message ="/test{\\\"url\\\":\"" + url + "\\\"}";
Please note that back-slash \ and double-quote " are specialized character and hence they need to be escaped using back-slash \.
Hence, \\ is used for \ and \" is used for " in String literal.
Output:
/test{\"url\":"sample\"}
After several tried, I found the solution:
StringBuilder sb=new StringBuilder();
sb.append("\"/test{");
sb.append("\"\\");
sb.append("\"");
sb.append("url\\\"");
sb.append(":");
sb.append("\\\"");
sb.append(url);
sb.append("\"\\}\"");
System.out.println(sb.toString());

How To Parse String In Java With * [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 2 years ago.
I have a string like this.
PER*IP**TE**1234567890*EM*sampleEmail#Email.com
How can I parse the string into multiple lines like this in Java?
PER
IP
TE
//Empty String
EM
1234567890
sampleEmail#Email.com
You could use a regex replacement:
String input = "PER*IP**TE*1234567890*EM*sampleEmail#Email.com";
String output = input.replaceAll("\\*", "\n");
System.out.println(output);
This prints:
PER
IP
TE
1234567890
EM
sampleEmail#Email.com
You can use String#split. Since * is a regular expression metacharacter, you need to escape it with a backslash or use Pattern#quote.
Arrays.stream("PER*IP**TE**1234567890*EM*sampleEmail#Email.com".split(Pattern.quote("*")))
.forEach(System.out::println);
String newstring = string.replace("*", "\n");
System.out.println(newstring);
now if you don't want that the empty line show up, use this:
String string = "PER*IP**TE**1234567890*EM*sampleEmail#Email.com"
String newstring = string.replaceAll("\\*+","*").replace("*", "\n");
System.out.println(newstring);

Regular Expression: No match found? [duplicate]

This question already has answers here:
How to escape text for regular expression in Java?
(8 answers)
What special characters must be escaped in regular expressions?
(13 answers)
Closed 5 years ago.
This is what I am trying to do...
Enter Pattern
//*//_//*
Enter Text
hello *_* how are you?
No match found
I know to avoid treating above characters as Metacharacters I need to use these escape sequences.
I don't know how to do with _ (underscore sigh)
I even tried
//* _ //*
Still it didn't work.
code
Scanner sc = new Scanner(System.in);
System.out.println("Enter pattern");
Pattern pattern = Pattern.compile(sc.nextLine());
System.out.println("Enter Text");
Matcher matcher = pattern.matcher(sc.nextLine());
boolean found = false;
while(matcher.find())
{
System.out.println("I found the text" + matcher.group() + "Starting index" + matcher.start() + "Ending at index" + matcher.end());
found = true;
}
if(!found)
{
System.out.println("No match found");
}
If you are trying to match the *_* part of the input, try the following pattern:
\*\_\*

replaceAll error [duplicate]

This question already has answers here:
String.replaceAll single backslashes with double backslashes
(5 answers)
Closed 5 years ago.
This is my regex. I want to find the opening and closing parentheses and replace them with "\(" and "\)".
word = word.replaceAll(Pattern.quote("("), "\\" + "(").replaceAll(Pattern.quote(")"), "\\" + ")");
This is the output if word = "word)":
New word is: word)
As you can see it didn't change a thing.
Try to use \\\\ like this :
word = word.replaceAll(Pattern.quote("("), "\\\\" + "(")
.replaceAll(Pattern.quote(")"), "\\\\" + ")");
or without Pattern.quote :
word = word.replaceAll("\\(", "\\\\(").replaceAll("\\)", "\\\\)");
or instead in your case you can just use replace :
word = word.replace("(", "\\(").replace(")", "\\)");
Two answers worked:
word.replace("(", "\\" + "(").replace(")", "\\" + ")"); – OH GOD SPIDERS
and
replacing \\ with \\\\ in the replaceAll - YCF_L.

Splitting of String delimited by '[' and ']' [duplicate]

This question already has answers here:
java regular expression to extract content within square brackets
(3 answers)
How do I split a string in Java?
(39 answers)
Closed 8 years ago.
I have some sampel data written on a file. The data are in the following format -
[Peter Jackson] [UK] [United Kingdom] [London]....
I have to extract the information delimited by '[' and ']'. So that I found -
Peter Jackson
UK
United Kingdom
London
...
...
I am not so well known with string splitting. I only know how to split string when they are only separated by a single character (eg - string1-string2-string3-....).
You should use regex for this.
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher results = p.matcher("[Peter Jackson] [UK] [United Kingdom] [London]....");
while (results.find()) {
System.out.println(results.group(1));
}
You can use this regex:
\\[(.+?)\\]
And the captured group will have your content.
Sorry for not adding the code. I don't know java
Is each item separated by spaces? if so, you could split by "\] \[" then replace all the left over brackets:
String vals = "[Peter Jackson] [UK] [United Kingdom] [London]";
String[] list = vals.split("\\] \\[");
for(String str : list){
str = str.replaceAll("\\[", "").replaceAll("\\]", "");
System.out.println(str);
}
Or if you want to avoid a loop you could use a substring to remove the beginning and ending brackets then just separate by "\\] \\[" :
String vals = " [Peter Jackson] [UK] [United Kingdom] [London] ";
vals = vals.trim(); //removes beginning whitspace
vals = vals.substring(1,vals.length()-1); // removes beginning and ending bracket
String[] list = vals.split("\\] \\[");
Try to replace
String str = "[Peter Jackson] [UK] [United Kingdom] [London]";
str = str.replace("[", "");
str = str.replace("]", "");
And then you can try to split it.
Splitting on "] [" should sort you, as in:
\] \[
Debuggex Demo
After this, just replace the '[' and the ']' and join using newline.

Categories

Resources