How to split a string in java based on a regex? - java

I have data as follows:
String s = "foo.com^null^[]";
String s1 = "bar.com^null^[{\"seen_first\":1357882827,\"seen_last\":1357882827,\"_id\":\"93.170.52.31\",\"exclude_from_publication\":false,\"locked\":false,\"agent\":\"domain_export\",\"web_published\":true,\"version\":\"IPv4\"},{\"seen_first\":1357882827,\"seen_last\":1357882827,\"_id\":\"93.170.52.21\",\"exclude_from_publication\":false,\"locked\":false,\"agent\":\"domain_export\",\"web_published\":true,\"version\":\"IPv4\"}]";
And note that third field.. it can be either [] or a json array.
And I am trying to parse these fields..
Here is my current attempt.
public static void check(String s) {
String [] tokens = s.split("^");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
System.out.println(tokens[2]);
if (tokens[2].trim().equals("[]")) {
System.out.println("here--> " +true);
}
System.out.println("---------");
}
What am i doing wrong?

^ is a metacharacter in a regex, meaning "the start of the string". You need to escape it:
String [] tokens = s.split("\\^");

Related

How do I remove all whitespaces from a string?

I'm trying to remove all whitespaces from a string. I've googled a lot and found only replaceAll() method is used to remove whitespace. However, in an assignment I'm doing for an online course, it says to use replace() method to remove all whitespaces and to use \n for newline character and \t for tab characters. I tried it, here's my code:
public static String removeWhitespace(String s) {
String gtg = s.replace(' ', '');
gtg = s.replace('\t', '');
gtg = s.replace('\n', '');
return gtg;
}
After compiling, I get the error message:
Error:(12, 37) java: empty character literal
Error:(13, 37) java: empty character literal
Error:(14, 37) java: empty character literal
All 3 refer to the above replace() code in public static String removeWhitespace(String s).
I'd be grateful if someone pointed out what I'm doing wrong.
There are two flavors of replace() - one that takes chars and one that takes Strings. You are using the char type, and that's why you can't specify a "nothing" char.
Use the String verison:
gtg = gtg.replace("\t", "");
Notice also the bug I corrected there: your code replaces chars from the original string over and over, so only the last replace will be effected.
You could just code this instead:
public static String removeWhitespace(String s) {
return s.replaceAll("\\s", ""); // use regex
}
Try this code,
public class Main {
public static void main(String[] args) throws Exception {
String s = " Test example hello string replace enjoy hh ";
System.out.println("Original String : "+s);
s = s.replace(" ", "");
System.out.println("Final String Without Spaces : "+s);
}
}
Output :
Original String : Test example hello string replace enjoy hh
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh
Another way by using char array :
public class Main {
public static void main(String[] args) throws Exception {
String s = " Test example hello string replace enjoy hh ";
System.out.println("Original String : "+s);
String ss = removeWhitespace(s);
System.out.println("Final String Without Spaces : "+ss);
}
public static String removeWhitespace(String s) {
char[] charArray = s.toCharArray();
String gtg = "";
for(int i =0; i<charArray.length; i++){
if ((charArray[i] != ' ') && (charArray[i] != '\t') &&(charArray[i] != '\n')) {
gtg = gtg + charArray[i];
}
}
return gtg;
}
}
Output :
Original String : Test example hello string replace enjoy hh
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh
If you want to specify an empty character for the replace(char,char) method, you should do it like this:
public static String removeWhitespace(String s) {
// decimal format, or hexadecimal format
return s.replace(' ', (char) 0)
.replace('\f', (char) 0)
.replace('\n', (char) 0)
.replace('\r', '\u0000')
.replace('\t', '\u0000');
}
But an empty character is still a character, therefore it is better to specify an empty string for the replace(CharSequence,CharSequence) method to remove those characters:
public static String removeWhitespace(String s) {
return s.replace(" ", "")
.replace("\f", "")
.replace("\n", "")
.replace("\r", "")
.replace("\t", "");
}
To simplify this code, you can specify a regular expression for the replaceAll(String,String) method to remove all whitespace characters:
public static String removeWhitespace(String s) {
return s.replaceAll("\\s", "");
}
See also:
• Replacing special characters from a string
• First unique character in a string using LinkedHashMap

Java - Cut a string programmatically

I have a string (URL) like this:
"https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp"
I need to extract the last part only i.e. 02_Cuppy_lol.webp.
How can I do that?
Thanks!
You can use substring() and lastIndexOf() here:
String value = completeString.substring(completeString.lastIndexOf("/") + 1);
You can split this text/url and get last part, for example:
String url = "https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] splittedUrl = url.split("/");
String lastPart = splittedUrl[splittedUrl.length()-1)];
you can use the method split().follow this example
public class Demo {
public static void main(String args[]){
String str ="https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] temp=str.split("/");
int lastIndex =temp.length-1;
String lastPart = temp[lastIndex];
System.out.println(lastPart);
}
}
Output-:
02_Cuppy_lol.webp

Substring based on special characters

I have to fetch the tablename and columnnames from a sql. For this I had split from clause data based on space and stored all the elements in a list, But now some of the columns having method calling or some other validations.
For ex some of columns :
max(TableName1.ColumnName1) --> TableName1.ColumnName1
concat('Q',TableName2.ColumnName2)} --> TableName2.ColumnName2
left(convert(varchar(90),TableName3.ColumnName3),1)}) --> TableName3.ColumnName3
Now I validate strings which are having .
Here I had only hint i.e (.) based on this I have to get right and left strings upto/before special characters.
Might get special characters like , ( )
import java.util.*;
import java.text.*;
import java.util.regex.*;
public class Parser {
private static Pattern p = Pattern.compile("(?![\\(\\,])([^\\(\\)\\,]*\\.[^\\(\\)\\,]+)(?=[\\)\\,])");
private static String getColumnName(String s) {
Matcher m = p.matcher(s);
while(m.find()) {
return m.group(1);
}
return "";
}
public static void main(String []args) {
String s1= "max(TableName1.ColumnName1)";
System.out.println(getColumnName(s1));
String s2= "concat('Q',TableName2.ColumnName2)}";
System.out.println(getColumnName(s2));
String s3= "left(convert(varchar(90),TableName3.ColumnName3),1)})";
System.out.println(getColumnName(s3));
}
}
Output:
TableName1.ColumnName1
TableName2.ColumnName2
TableName3.ColumnName3
You can use a regular expression like [(),{}] to split the array into tokens, and then just select the token with the "." sign in it. For example:
public static String getColumnName (String input) {
if (StringUtils.isEmpty(input)) return input;
String[] tokens = input.split("[(),{}]");
for (String token: tokens) {
if (token.contains(".")) return token;
}
return input;
}
public static void main(String args[]) throws Exception {
//The two tokens will be "max", "TableName1.ColumnName1".
String test1 = "max(TableName1.ColumnName1)";
//The three tokens will be "concat", "Q" and "TableName2.ColumnName2".
String test2 = "concat('Q',TableName2.ColumnName2)}";
//The six tokens will be "left", "convert", "varchar",
//"90", "", "1" and "TableName3.ColumnName3".
String test3 = "left(convert(varchar(90),TableName3.ColumnName3),1)})";
System.out.println(getColumnName(test1));
System.out.println(getColumnName(test2));
System.out.println(getColumnName(test3));
}
The print out will give you:
TableName1.ColumnName1
TableName2.ColumnName2
TableName3.ColumnName3

How to replace special character In Android?

I have to create file with user define name. If User can use the special character then i want to replace that special character with my specific string. i found the method like this.
String replaceString(String string) {
return string.replaceAll("special_char","");
}
but how to use this method.?
relpaceAll method is required regular expression and replace string.
string.replaceAll("regularExpression","replaceString");
You can use this regular expression :
"[;\\/:*?\"<>|&']"
e.g.
String replaceString(String string) {
return string.replaceAll("[;\\/:*?\"<>|&']","replaceString");
}
Try
regular expression
static String replaceString(String string) {
return string.replaceAll("[^A-Za-z0-9 ]","");// removing all special character.
}
call
public static void main(String[] args) {
String str=replaceString("Hello\t\t\t.. how\t\t are\t you."); // call to replace special character.
System.out.println(str);
}
output:
Hello how are you
use below function to replace your string
public static String getString(String p_value)
{
String p_value1 = p_value;
if(p_value1 != null && ! p_value1.isEmpty())
{
p_value1 = p_value1.replace("Replace string from", "Replace String to");
return p_value1;
}
else
{
return "";
}
}
example
Replace string from = "\n";
Replace String to = "\r\n";
after using above function \n is replace with \r\n
**this method make two line your string data after specific word **
public static String makeTwoPart(String data, String cutAfterThisWord){
String result = "";
String val1 = data.substring(0, data.indexOf(cutAfterThisWord));
String va12 = data.substring(val1.length(), data.length());
String secondWord = va12.replace(cutAfterThisWord, "");
Log.d("VAL_2", secondWord);
String firstWord = data.replace(secondWord, "");
Log.d("VAL_1", firstWord);
result = firstWord + "\n" + secondWord;
return result;
}

Java : Replacing Last character of a String and First character of the String

I want to add Two java JSON String manually , so for this i need to remove "}" and replace it with comma "," of first JSON String and remove the first "{" of the second JSON String .
This is my program
import java.util.Map;
import org.codehaus.jackson.type.TypeReference;
public class Hi {
private static JsonHelper jsonHelper = JsonHelper.getInstance();
public static void main(String[] args) throws Exception {
Map<String, Tracker> allCusts = null;
String A = "{\"user5\":{\"Iden\":4,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
String B = "{\"user1\":{\"Iden\":4,\"Num\":1},\"user3\":{\"Iden\":6,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
String totalString = A + B;
if (null != totalString) {
allCusts = (Map<String, Tracker>) jsonHelper.toObject(
totalString, new TypeReference<Map<String, Tracker>>() {
});
}
System.out.println(allCusts);
}
}
When adding two Strings A + B
I want to remove the last character of "}" in A and replace it with "," and remove the FIrst character of "{" in B .
SO this should it look like .
String A = "{\"user5\":{\"Iden\":4,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1},";
String B = "\"user1\":{\"Iden\":4,\"Num\":1},\"user3\":{\"Iden\":6,\"Num\":1},\"user2\":{\"Iden\":5,\"Num\":1}}";
I have tried
String Astr = A.replace(A.substring(A.length()-1), ",");
String Bstr = B.replaceFirst("{", "");
String totalString = Astr + Bstr ;
With this i was getting
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition
please suggest .
{ is a control character for Regular Expressions, and since replaceFirst takes a string representation of a Regular Expression as its first argument, you need to escape the { so it's not treated as a control character:
String Bstr = B.replaceFirst("\\{", "");
I would say that using the replace methods is really overkill here since you're just trying to chop a character off of either end of a string. This should work just as well:
String totalString = A.substring(0, A.length()-1) + "," + B.substring(1);
Of course, regex doesn't look like a very good tool for this. But the following seem to work:
String str = "{..{...}..}}";
str = str.replaceFirst("\\{", "");
str = str.replaceFirst("}$", ",");
System.out.println(str);
Output:
..{...}..},
Some issues in your first two statements. Add 0 as start index in substring method and leave with that. Put \\ as escape char in matching pattern and ut a , in second statement as replacement value.
String Astr = A.substring(0, A.length()-1);//truncate the ending `}`
String Bstr = B.replaceFirst("\\{", ",");//replaces first '{` with a ','
String totalString = Astr + Bstr ;
Please note: There are better ways, but I am just trying to correct your statements.

Categories

Resources