how to append a backquote in java string - java

Someone please help me how to append a backquote in a string in java.
I tried with String result="`"+value+"`";
I need to append the backquote before and after the string.
What is the correct way?

You should scape " using \"
Eg: "\""+value+"\"";
Ideone demo.
Edit: OP want to use backquote(```) so answer will be following and no need to scape.
"`"+value+"`"
Ideone demo.

When we use literal strings in Java, we use the quote (") character to indicate the beginning and ending of a string. For example, to declare a string called myString, we could this :-
String myString = "this is a string";
But what if we wanted to include a quote (") character WITHIN the string. We can use the \ character to indicate that we want to include a special character, and that the next character should be treated differently. \" indicates a quote character, not the termination of a string.
public static void main (String args[])
{
System.out.println ("If you need to 'quote' in Java");
System.out.println ("you can use single \' or double \" quote");
}
This allows us to include quote characters within a string.

Related

ReplaceAll when it is not alpha characters

I need to replace all the occurrences of a word in a String when it is between non alpha characters(digits, blankspaces...etc) or at the beginning or the end of the String for a $0. However, my Regex pattern does not seem to work when I use replaceAll.
I have tried several solutions which I found on the web, like Pattern.quote, but the pattern doesn't seem to work. However, it works perfectly on https://regexr.com/
public static final String REPLACE_PATTERN = "(?<=^|[^A-Za-z])(%s)(?=[^A-Za-z]|$)";
String patternToReplace = String.format(REPLACE_PATTERN, "a");
inputString = inputString.replaceAll(Pattern.quote(patternToReplace), "$0");
For example, with the string and the word "a":
a car4is a5car
I expect the output to be:
$0 car4is $05car
Just change from inputString.replaceAll(Pattern.quote(patternToReplace), "$0"); to inputString.replaceAll(patternToReplace, "\\$0");
I have tested with this code :
public static final String REPLACE_PATTERN = "(?<=^|[^A-Za-z])(%s)(?=[^A-Za-z]|$)";
String patternToReplace = String.format(REPLACE_PATTERN, "a");
inputString = inputString.replaceAll(patternToReplace, "\\$0");
System.out.println(inputString);
Output :
$0 car4is $05car
Hope this helps you :)
When you want to replace the matching parts of the string with "$0", you have to write it
"\\$0". This is because $0 has a special meaning: The matching string. So you replace the string by itself.
You are quoting the wrong thing. You should not quote the pattern. You should quote "a" - the part of the pattern that should be treated literally.
String patternToReplace = String.format(REPLACE_PATTERN, Pattern.quote("a"));
If you are never going to put anything other letters in the second argument of format, then you don't need to quote at all, because letters do not have special meaning in regex.
Additionally, $ has special meaning when used as the replacement, so you need to escape it:
inputString = inputString.replaceAll(patternToReplace, "\\$0");
Pattern.quote() returns regex literal and everything in-between is treated like a text.
You should use Matcher to replace all string occurrences. Besides that, as #Donat pointed out, $0 is treated like a regex variable, so you need to escape it.
inputString = Pattern.compile(patternToReplace).matcher(inputString).replaceAll("\\$0");

Check whether the string contains backslash or not?

In Java, \' denotes a single quotation mark (single quote) character, and \" denotes a double quotation mark (double quote) character.
So, String s = "I\'m a human."; works well.
However, String s = "I'm a human." does not make any compile errors, either.
Likewise, char c = '\"'; works, but char c = '"'; also works.
But I need to detect whether the string contains backslash or not:
"abcd'" does not contain backslash
"abcd\'" contains backslash.
I need to distinguish whether the string contains backslash or not.
You can't. The're called escape sequences for a reason. For example, \n once put in a String, cannot match a literal \ against itself. It's gone. All that's left, is a new-line.
Remember \ is used to escape a character. It itself doesn't remain a part of the String.
However, you can check for a literal \ by doing a simple contains like
String s = "abcd\\";
System.out.println(s.contains("\\"));
"abcd\" is not a valid string in java.
Here java treated \" as an escape sequence character("). So, if you want to put a backslash in a string then you need to use \ with escape sequence character.
String "abcd\'" has not contained backslash character. It has an escape sequence character \'.
Escape characters (also called escape sequences or escape codes) in
general are used to signal an alternative interpretation of a series
of characters. In Java, a character preceded by a backslash (\) is an
escape sequence and has special meaning to the java compiler.
When an escape sequence is encountered in a print statement, the
compiler interprets it accordingly. For example, if you want to put
quotes within quotes you must use the escape sequence, \", on the
interior quotes. To print the sentence: She said "Hello!" to me. you
should write:
System.out.println("She said \"Hello!\" to me.");
// Java program to illustrate to find a character
// in the string.
import java.io.*;
public static void main (String[] args)
{
// This is a string in which a character
// to be searched.
String str = "gee\\k";
// Returns index of first occurrence of character.
int firstIndex = str.indexOf('\\');
System.out.println("First occurrence of char '\\'" +
" is found at : " + firstIndex);
}
if(string.contains("\\")){
//TODO do your code here
}
\ is used as for escape sequence in Java.
If you want to print backslash in the string you just have to print "abcd\\".
For your example it would be:
boolean containsBs = "abcd\\".contains("\\");
When you are using Strings you do not need to use the escape character(backslash) for single quotation marks. Likewise when using char you do not need to escape the double quotation mark.
String use double quotation mark while chars use single quotation mark. You need to use the escape character for double quote in Strings and for simple quote in chars.
String ex="I'm an example";
String ex2="My name is \"example\"";
char c='"';
char c2='\'';
If you want to find out if a String contains backslash
String ex="abcd";
String ex2="abcd\\";
ex.contains("\\"); //false
ex.contains("\\"); //true
The first backslash is for escaping and the second is the character.

What is the purpose of Escape Sequence \' in java?

if I print ' (single quote) in the System.out.println() I can get exact output.
Like :
System.out.println("test'test");
output: test'test
What is the purpose of using \' escape sequence in java?
This also gives me the same output.
System.out.println("test\'test");
output: test'test
pls explain what is the main purpose of \' escape sequence in java
It's for use in character literals:
char c = '\'';
Without that, it would be painful to get a single apostrophe as a char.
This is useful for character literals stored in char.
Imagine you want a character constant to just hold a '. You could do:
public static final char SINGLE_QUOTE = '';
This won't work as it only is an empty character, but we want a single quote. Hence the escape character \'.
public static final char SINGLE_QUOTE = '\'';
If you print it on System.out.println, you'll see the difference.
For an exercise, try and take your exact example and see if you can print a double quote literal " without escaping it. You'll see it's not possible. You will have to escape it with \".
Reference: String literals and Escape Sequences for Character and String Literals.

String split by dot - Java

I have the following code:
public static void main(String[] args) {
String str = "21.12.2015";
String delim = "\\.";
String[] st = str.split(delim);
System.out.println(st[0]+"."+st[1]+"."+st[2]); // 1
System.out.println(st[0]+delim+st[1]+delim+st[2]); // 2
}
Now, line 1 is printing expected output - 21.12.2015. But why line 2 is not giving same output as line 1? Why it is printing like 21\.12\.2015?
EDIT:
Actually in my requirement, the delimiter changes dynamically for each string(- or / or .). So I am trying to assign the delimiter to a variable and then split by it and finally print it as a pattern(say dd.mm.yy or dd-mm-yy or etc). For other delimiters it's fine, but for dot it's coming like dd\.mm\.yy. How shall I achieve the expected result?
This handles all delim values:
String str = "21.12.2015";
String delim = "."; // or "-" or "?" or ...
String[] st = str.split(java.util.regex.Pattern.quote(delim));
When you say split you are using delim as a regex pattern. It is treated differently. Please have a look to this regular expression.
But when you are using delim in sysout you are using it as string. the difference is obviuos
When you create the delim variable, you escape the backslash. The real value of the delim variable is \..
Just create the delim variable as (the backslash is useless):
String delim = ".";
because of delim = "\\.", while spliting "\\." is required.
You are using the split method from the String class, which uses regular expression for splitting the the string.
Due to this the \\. will split the string by every dot and needs to be escaped, since the dot itself is part of the regular expression.
In the second part you are simply printing the string, in which the backlash itself is a indicator for an string expression (like \n as a new line).
The double backlash just excludes this string expression to be written as a normal string "\n" in this case, and thats why you get the "\." result
For better understanding, try to delete one of the backslashes in the delim variable, and the java interpreter will throw an error since "\." is not a string expression
\\. is a regex String to parse . literally. You need it while splitting (since split() expects a regex String).
While printing, you need to use . directly isntead of "\\." because println() doesn't need a regex.
Split method uses regex for splitting so you will need to provide as \\. while this is not the scenario when you are printing it, you just need to use '.' directly.
In Java \\. will be printed as \. as \\ is considered as a single backslash.

Why regular expression in Java cannot recognize \s as space character?

I read from a lot of webpage (for example: http://www.wellho.net/regex/java.html), they all mentioned that \s could represent any space charactor. But when I use \s in Java, it is not an eligible expression.
Anyone know the reason?
Backslashes inside strings need to be quoted in order to work.
For example, the following works fine:
public class testprog {
public static void main(String args[]) {
String s = "Hello there";
System.out.println (s.matches(".*\\s.*"));
}
}
outputting:
true
If you use a string like "\s", you should get an error along the lines of:
Invalid escape sequence - valid ones are \b \t \n \f \r \" \' \\
from your compiler since \s is not a valid escape sequence (for strings, I mean, not regexes).

Categories