How can I trim beginning and ending double quotes from a string? - java

I would like to trim a beginning and ending double quote (") from a string.
How can I achieve that in Java? Thanks!

You can use String#replaceAll() with a pattern of ^\"|\"$ for this.
E.g.
string = string.replaceAll("^\"|\"$", "");
To learn more about regular expressions, have al ook at http://regular-expression.info.
That said, this smells a bit like that you're trying to invent a CSV parser. If so, I'd suggest to look around for existing libraries, such as OpenCSV.

To remove the first character and last character from the string, use:
myString = myString.substring(1, myString.length()-1);

Also with Apache StringUtils.strip():
StringUtils.strip(null, *) = null
StringUtils.strip("", *) = ""
StringUtils.strip("abc", null) = "abc"
StringUtils.strip(" abc", null) = "abc"
StringUtils.strip("abc ", null) = "abc"
StringUtils.strip(" abc ", null) = "abc"
StringUtils.strip(" abcyx", "xyz") = " abc"
So,
final String SchrodingersQuotedString = "may or may not be quoted";
StringUtils.strip(SchrodingersQuotedString, "\""); //quoted no more
This method works both with quoted and unquoted strings as shown in my example. The only downside is, it will not look for strictly matched quotes, only leading and trailing quote characters (ie. no distinction between "partially and "fully" quoted strings).

If the double quotes only exist at the beginning and the end, a simple code as this would work perfectly:
string = string.replace("\"", "");

Kotlin
In Kotlin you can use String.removeSurrounding(delimiter: CharSequence)
E.g.
string.removeSurrounding("\"")
Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter.
Otherwise returns this string unchanged.
The source code looks like this:
public fun String.removeSurrounding(delimiter: CharSequence): String = removeSurrounding(delimiter, delimiter)
public fun String.removeSurrounding(prefix: CharSequence, suffix: CharSequence): String {
if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
return substring(prefix.length, length - suffix.length)
}
return this
}

This is the best way I found, to strip double quotes from the beginning and end of a string.
someString.replace (/(^")|("$)/g, '')

First, we check to see if the String is doubled quoted, and if so, remove them. You can skip the conditional if in fact you know it's double quoted.
if (string.length() >= 2 && string.charAt(0) == '"' && string.charAt(string.length() - 1) == '"')
{
string = string.substring(1, string.length() - 1);
}

Using Guava you can write more elegantly CharMatcher.is('\"').trimFrom(mystring);

I am using something as simple as this :
if(str.startsWith("\"") && str.endsWith("\""))
{
str = str.substring(1, str.length()-1);
}

To remove one or more double quotes from the start and end of a string in Java, you need to use a regex based solution:
String result = input_str.replaceAll("^\"+|\"+$", "");
If you need to also remove single quotes:
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
NOTE: If your string contains " inside, this approach might lead to issues (e.g. "Name": "John" => Name": "John).
See a Java demo here:
String input_str = "\"'some string'\"";
String result = input_str.replaceAll("^[\"']+|[\"']+$", "");
System.out.println(result); // => some string

Edited: Just realized that I should specify that this works only if both of them exists. Otherwise the string is not considered quoted. Such scenario appeared for me when working with CSV files.
org.apache.commons.lang3.StringUtils.unwrap("\"abc\"", "\"") = "abc"
org.apache.commons.lang3.StringUtils.unwrap("\"abc", "\"") = "\"abc"
org.apache.commons.lang3.StringUtils.unwrap("abc\"", "\"") = "abc\""

The pattern below, when used with java.util.regex.Matcher, will match any string between double quotes without affecting occurrences of double quotes inside the string:
"[^\"][\\p{Print}]*[^\"]"

Matcher m = Pattern.compile("^\"(.*)\"$").matcher(value);
String strUnquoted = value;
if (m.find()) {
strUnquoted = m.group(1);
}

Modifying #brcolow's answer a bit
if (string != null && string.length() >= 2 && string.startsWith("\"") && string.endsWith("\"") {
string = string.substring(1, string.length() - 1);
}

private static String removeQuotesFromStartAndEndOfString(String inputStr) {
String result = inputStr;
int firstQuote = inputStr.indexOf('\"');
int lastQuote = result.lastIndexOf('\"');
int strLength = inputStr.length();
if (firstQuote == 0 && lastQuote == strLength - 1) {
result = result.substring(1, strLength - 1);
}
return result;
}

find indexes of each double quotes and insert an empty string there.

public String removeDoubleQuotes(String request) {
return request.replace("\"", "");
}

Groovy
You can subtract a substring from a string using a regular expression in groovy:
String unquotedString = theString - ~/^"/ - ~/"$/

Scala
s.stripPrefix("\"").stripSuffix("\"")
This works regardless of whether the string has or does not have quotes at the start and / or end.
Edit: Sorry, Scala only

Related

Remove domain name from string java

I have a string which looks like this
String str = "domain\ABC";
String str = "domain1\DEF";
How do i write a common function to remove the "domain\" or "domain1\" and just have the string after the the '\'. I tried a couple of different ways but none seem to work.
This is what i have tried.
String[] str = remoteUser.split(remoteUser, '\\');
No need for split() or regex for this, as that is overkill. It's a simple indexOf() operation.
How do i write a common function ... ?
Like this:
public static String removeDomain(String input) {
return input.substring(input.indexOf('/') + 1);
}
The code relies on the fact indexOf() returns -1 if / is not found, so the + 1 will make that 0 and substring(0) then returns input string as-is.
Try it like this.
String str = "domain\\ABC";
String[] split = str.split("\\\\");
//Assign the second element of the array. This only works if you know for sure that there is only one \ in the string.
String withoutSlash = split[1];
Hope it helps.
You might use replaceAll:
System.out.println("domain\\ABC".replaceAll("^.*\\\\",""));
It will replace everything starting at the beginning of the string, until \ symbol.
Try this:
static String getPath(String url) {
int pos = url.indexOf('\');
return pos >= 0 ? url.substring(pos + 1) : url;
}

How to remove single and double quotes at both ends of a string

I would like to remove single or double quotes from both ends of a string. The string may contain additional quotes or/and double quotes which shall remain untouched - so removeAll() is not an option.
String one = "\"some string\"";
String two = "'some \"other string\"'";
// expected result
// some string
// some "other string"
What I tried so far:
two = two.replace("/^[\"\'])|([\"\']$/g", "");
The following would work but there must be a much more elegant way to achieve this..
if ((one != null && one.length() > 1) && ((one.startsWith("\"") && one.endsWith("\"")) ||
(one.startsWith("\'") && one.endsWith("\'")))) {
one = one.substring(1, one.length() - 1);
}
Any ideas?
Update / clarification
My use case is the command line interface of an app, where the user can also drag files/paths into, instead of typing them.
Under Windows the dragged files are beeing surrounded by double quotes, under Linux with single quotes. All I want to do is get rid of them. So in my use case the quotes are always symetric (they match).
But I can perfectly live with a solution, which would strip them even if they wouldn't match, because they always do
Option 1: Removing all single and double quotes from start and end
You can use replaceAll which accepts a regular expression - replace doesn't - and do it twice, once for quotes at the start of the string and once for quotes at the end:
public class Test {
public static void main(String[] args) {
String text = "\"'some \"other string\"'";
String trimmed = text
.replaceAll("^['\"]*", "")
.replaceAll("['\"]*$", "");
System.out.println(trimmed);
}
}
The ^ in the first replacement anchors the quotes to the start of the string; the $ in the second anchors the quotes to the end of the string.
Note that this doesn't try to "match" quotes at all, unlike your later code.
Option 2: Removing a single quote character from start and end, if they match
String trimmed = text.replaceAll("^(['\"])(.*)\\1$", "$2");
This will trim exactly one character from the start and end, if they both match. Sample:
public class Test {
public static void main(String[] args) {
trim("\"foo\"");
trim("'foo'");
trim("\"bar'");
trim("'bar\"");
trim("\"'baz'\"");
}
static void trim(String text) {
String trimmed = text.replaceAll("^(['\"])(.*)\\1$", "$2");
System.out.println(text + " => " + trimmed);
}
}
Output:
"foo" => foo
'foo' => foo
"bar' => "bar'
'bar" => 'bar"
"'baz'" => 'baz'
To complete Jon Skeet response, if you want to remove quotes only if there is one on the beginning AND one on the end you can do :
public String removeQuotes(String str) {
Pattern pattern = Pattern.compile("^['\"](.*)['\"]$");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
return matcher.group(1);
} else {
return str;
}
}
if you are looking in javascript try this :
function t(k){
var l="\"\'"; //you can add more chars here.
if (l.indexOf(k[0])>-1) {
return t(k.substr(1,k.length));
} else if (l.indexOf(k[k.length-1])>-1) {
return t(k.substr(0,k.length-1));
} else {
return k;
}
}
One possible way with using replaceFirst():
String one = "\"some string\"";
System.out.println("one: " + one);
one = one.replaceFirst("\"", "");
String reversed = new StringBuilder(one).reverse().toString();
one = one.replaceFirst("\"", "");
one = new StringBuilder(reversed).reverse().toString();
System.out.println("result: " + one);

How to split a String based on conditions

Hi I need to split a String in java based on conditions
the String might be in two formats
1. IF the format is like this WG/A/0-5 then I need to check if the last part starts with "0-" then I need the middle part to be extracted (ie:"A")
2.The Second format is WG/A/3-3 here it is 3-3 ie:other than 0) here I need to extract (A/3) .
I have tried like this
String parent = StringPool.BLANK;
if(wgCode.split(StringPool.FORWARD_SLASH)[2].startsWith("0-")) {
parent = wgCode.split(StringPool.FORWARD_SLASH)[1];
} else if(!wgCode.split(StringPool.FORWARD_SLASH)[2].startsWith("0-")) {
parent = wgCode.split(StringPool.FORWARD_SLASH)[1]+"/"+wgCode.split(StringPool.FORWARD_SLASH)[2].split("-")[0];
}
_log.info("parent parent"+parent);
Use Regular Expressions and String.contains to check your conditions and String.indexOf and String.substring to split your String.
The following method will work for your example:
public String getString(String input)
{
if(input.matches(".*/.*/0.*"))
{
String yourString = input.substring(input.indexOf("/")+1);
yourString = yourString.substring(0, yourString.indexOf("/"));
return yourString;
}
else
{
String yourString = input.substring(input.indexOf("/")+1);
yourString = yourString.substring(0, yourString.indexOf("/")+2);
return yourString;
}
}
With the regular expression .*/.*/0.* you find all Strings that start with a 0 after the second /.
use String#contains(String) to check whether 0- is there nor not.
String str="WG/A/0-5";
String str1="WG/A/3-3";
if(str.contains("0-"))
System.out.println(str.substring(str.indexOf("/")+1,str.indexOf("/",str.indexOf("/") + 1)));//A
if(!str1.contains("0-"))
System.out.println(str1.substring(str1.indexOf("/")+1,str1.indexOf("-")));//A/3
Maybe something like this:
String input = "WG/A/0-5";
String[] parts = input.split("/");
if( parts[2].charAt(0) == '0' ){
......
String charAt, substring should solve your problem:
String myValue = input.charAt(5) == '0' ? input.substring(3, 4) : input
.substring(3, 6);

How to replace comma (,) with a dot (.) using java

I am having a String str = 12,12
I want to replace the ,(comma) with .(Dot) for decimal number calculation,
Currently i am trying this :
if( str.indexOf(",") != -1 )
{
str.replaceAll(",","\\.");
}
please help
Your problem is not with the match / replacement, but that String is immutable, you need to assign the result:
str = str.replaceAll(",","."); // or "\\.", it doesn't matter...
Just use replace instead of replaceAll (which expects regex):
str = str.replace(",", ".");
or
str = str.replace(',', '.');
(replace takes as input either char or CharSequence, which is an interface implemented by String)
Also note that you should reassign the result
str = str.replace(',', '.')
should do the trick.
if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }
or even better
str = str.replace(',', '.');
Just use str.replace(',', '.') - it is both fast and efficient when a single character is to be replaced. And if the comma doesn't exist, it does nothing.
For the current information you are giving, it will be enought with this simple regex to do the replacement:
str.replaceAll(",", ".");
in the java src you can add a new tool like this:
public static String remplaceVirguleParpoint(String chaine) {
return chaine.replaceAll(",", "\\.");
}
Use this:
String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12
hope help you.
If you want to change it in general because you are from Europe and want to use dots instead of commas for reading an input with a scaner you can do it like this:
Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.US);
System.out.println(sc.locale().getDisplayCountry());
Double accepted with comma instead of dot

Last substring of string

In Java we have indexOf and lastIndexOf. Is there anything like lastSubstring? It should work like :
"aaple".lastSubstring(0, 1) = "e";
Not in the standard Java API, but ...
Apache Commons has a lot of handy String helper methods in StringUtils
... including
StringUtils.right("apple",1)
http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html#right(java.lang.String,%20int)
just grab a copy of commons-lang.jar from commons.apache.org
Generalizing the other responses, you can implement lastSubstring as follows:
s.substring(s.length()-endIndex,s.length()-beginIndex);
Perhaps lasIndexOf(String) ?
Wouldn't that just be
String string = "aaple";
string.subString(string.length() - 1, string.length());
?
You can use String.length() and String.length() - 1
For those looking to get a substring after some ending delimiter, e.g. parsing file.txt out of /some/directory/structure/file.txt
I found this helpful: StringUtils.substringAfterLast
public static String substringAfterLast(String str,
String separator)
Gets the substring after the last occurrence of a separator. The separator is not returned.
A null string input will return null. An empty ("") string input will return the empty string. An empty or null separator will return the empty string if the input string is not null.
If nothing is found, the empty string is returned.
StringUtils.substringAfterLast(null, *) = null
StringUtils.substringAfterLast("", *) = ""
StringUtils.substringAfterLast(*, "") = ""
StringUtils.substringAfterLast(*, null) = ""
StringUtils.substringAfterLast("abc", "a") = "bc"
StringUtils.substringAfterLast("abcba", "b") = "a"
StringUtils.substringAfterLast("abc", "c") = ""
StringUtils.substringAfterLast("a", "a") = ""
StringUtils.substringAfterLast("a", "z") = ""
I'm not aware of that sort of counterpart to substring(), but it's not really necessary. You can't efficiently find the last index with a given value using indexOf(), so lastIndexOf() is necessary. To get what you're trying to do with lastSubstring(), you can efficiently use substring().
String str = "aaple";
str.substring(str.length() - 2, str.length() - 1).equals("e");
So, there's not really any need for lastSubstring().

Categories

Resources