split the special charater contain inside the string - java

I have a String """JBL#gmail.com from which I want to remove the """ which is located at the front of the email address. I tried to use split, but unfortunately it didn't work.
Here is my code:
String [] sender1 = SA1.split(" ");
String str1 = sender1[0];
System.out.println("the str1 is :"+str1);
String [] sender2 = str1.split("\\\"");
String str2 = sender2[0];
String str3 = sender2[1];
System.out.println("the str2 is :"+str2);
System.out.println("the str3 is :"+str3);
Here is my code output-
the str1 is :"""JBL#gmail.com""
the str2 is :
the str3 is :
My SA1 will contain """JBL#gmail.com"" <JBL#gmail.com>". The email address can be a mix of lower/upper case letters, numbers, and etc.

If SA1 does in fact contain
"\"\"\"JBL#gmail.com\"\" <JBL#gmail.com>\""
then you can use Pattern/Matcher with a Regular Expression of "<(.*?)>" to retrieve the E-Mail Address from the String:
String sa1 = "\"\"\"JBL#gmail.com\"\" <JBL#gmail.com>\"";
String email = "";
Pattern pattern = Pattern.compile("<(.*?)>");
Matcher matcher = pattern.matcher(sa1);
while (matcher.find()) {
// Is a match found?
if (!matcher.group(1).equals("")) {
// There is so place the match into the
// email variable.
email = matcher.group(1);
}
}
// Display the E-Mail Address in Console Window.
System.out.println("E-Mail Address is: " + email);
Console window will display:
E-Mail Address is: JBL#gmail.com
Regular Expression Explanation:

You can obtain the email in the first part of the string by removing all quotation marks (replace("\"", "")), spliting by spaces (split(" ")), and taking the first element in the split ([0]):
String str = "\"\"\"JBL#gmail.com\"\" <JBL#gmail.com>\"";
str.replace("\"", "").split(" ")[0];
Note that the second element would produce <JBL#gmail.com>.

"fdsd\"\"\" dsd".split("\"\"\"")
you have to use
"yourWords".split("\"\"\"")

String s= "\"\"\"JBL#gmail.com\"\" <JBL#gmail.com>\"".
split("<")[1].replace(">", "").replace("\"", "");

Related

Java Regex multi delimiter split in order

I am trying to split a string having multi-delimiters in it but want to first check if the string satisfies the regex and then split based on it.
Example:-
The testString will contain ://,:,#,:,/ these characters in specific order and I need to first check if the given string satisfies the pattern or not and if satisfy then split it. The string other characters can also contain these in it but I need to split based on order of these ://,:,#,:,/
String testString = "aman://jaspreet:raman!#127.0.0.1:5031/test";
String[]tokens = testString.split("://|\\:|#|\\:|\\/");
for(String s:tokens) {
System.out.println(s);
}
Here above I have tried the regex to split but it doesn't split by checking in order. It just checks if any given regex character exists in string or not and then splits based on it.
If you first validate the pattern, then you shouldn't do split() after. Use capturing groups to gather the data you already validated.
E.g. in a simple case, foo#bar, with separator #, you would validate with ^([^#]+)#(.+)$, i.e. match and capture text up to #, match but don't capture the #, then match and capture the rest:
Pattern p = Pattern.compile("^([^#]+)#(.+)$");
Matcher m = p.matcher("foo#bar");
if (! m.matches()) {
// invalid data
} else {
String a = m.group(1); // a = "foo"
String b = m.group(2); // b = "bar"
// use a and b here
}
For the matching in the question, a lenient pattern could be:
^(.*?)://(.*?):(.*?)#(.*?):(.*?)/(.*)$
You would then use code above, but with:
String scheme = m.group(1); // "aman"
String user = m.group(2); // "jaspreet"
String password = m.group(3); // "raman!"
String host = m.group(4); // "127.0.0.1"
String port = m.group(5); // "5031"
String path = m.group(6); // "test"
For a stricter matching, replace .*? with a pattern that only matches allowed characters, e.g. [^:]+ if it cannot be empty and cannot contain colons.
Alternatively, you could just use the URI class to parse the URL string.
String testString = "aman://jaspreet:raman!#127.0.0.1:5031/test";
URI uri = URI.create(testString);
String scheme = uri.getScheme(); // "aman"
String userInfo = uri.getUserInfo(); // "jaspreet:raman!"
String host = uri.getHost(); // "127.0.0.1"
String port = uri.getPort(); // "5031"
String path = uri.getPath(); // "test"

How can i replace this?

How can I replace this
String str = "KMMH12DE1433";
String pattern = "^[a-z]{2}([0-9]{2})[a-z]{1,2}([0-9]{4})$";
String str2 = str.replaceAll(pattern, "repl");
Log.e("Founded_words2",str2);
What I got: KMMH12DE1433
What I want: MH12DE1433
Try it like this using a proper java.util.regex.Pattern and a java.util.regex.Matcher:
String str = "KMMH12DE1433";
//Make the pattern, case-insensitive using (?i)
Pattern pattern = Pattern.compile("(?i)[a-z]{2}([0-9]{2})[a-z]{1,2}([0-9]{4})");
//Create the Matcher
Matcher m = pattern.matcher(str);
//Check if we find anything
if(m.find()) {
//Use what you found - with proper capturing groups you
//gain access to parts of your pattern as needed
System.out.println("Found this: " + m.group());
}
If you just want to remove the first two characters and if the first two characters will always be uppercase letters:
String str = "KMMH12DE1433";
String pattern = "^[A-Z]{2}";
String str2 = str.replaceAll(pattern, "");
Log.e("Output string: ", str2);
try this :
String a = "KMMH12DE1433";
String pattern = "^[A-Z]{2}";
String rs = a.replaceAll(pattern,"");
Please change like this
String ans=str.substring(0);

Split the string with hyphen symbol multiple occurrence using regex /java

Getting the string value using the below xpath
String noAndDate = driver.findElement(By.xpath("//*[#id='c38']/div/table/tbody/tr[1]/td/strong")).getText();
Output of the above string = 2928554 - 2009-09-18 (BOPI 2009-38)
my expected output
2928554
2009-09-18
i tried below split, but i'm not getting my expected output
String[] words = noAndDate.split("-");
Please advice/help me
You can instead try splitting on a regex alternation which looks for a hyphen surrounded by whitespace, or pure whitespace:
String input = "2928554 - 2009-09-18 (BOPI 2009-38)";
String[] parts = input.split("(\\s+-\\s+|\\s+)");
System.out.println(parts[0]);
System.out.println(parts[1]);
Demo
Try the below code-
String str = "2928554 - 2009-09-18 (BOPI 2009-38)";
String str1 = str.split(" - | ")[0];
String str2 = str.split(" - | ")[1];
This will return str1 as 2928554 and str2 as 2009-09-18.
Hope this will help you !
Just split with regex will do.
String given = "2928554 - 2009-09-18 (BOPI 2009-38)";
String [] splitted = given.split(" - |\\s+");
String result = splitted[0] +", "+splitted[1];
System.out.println(result);
prints
2928554, 2009-09-18
Use Regex capture groups, here you can see what you want in 2 groups:
(\d+)\s*-\s*(\d+\-\d+\-\d+)
() = group
Try this:
String[] words = noAndDate.split(" ");
then
System.out.println(words[0]);
System.out.println(words[2]);

How to append to beginning of java string using replace with regex?

How can I use java string replaceAll or replaceFirst to append to beginning?
String joe = "Joe";
String helloJoe = joe.replaceAll("\\^", "Hello");
Desired Output: "Hello Joe"
You don't need to escape ^ because ^ is a special meta character in regex which matches the start of a line.
String helloJoe = whatever.replaceFirst("^", "Hello ");
You could perform a simple String append with +, or String.format(String, Object...) like
String whatever = "Joe";
String helloJoe = String.format("Hello %s", whatever);
// String helloJoe = "Hello " + whatever;
System.out.println(helloJoe);
Output is (as requested)
Hello Joe

I want to check if a word or a set of words exists in a String

My requirement is to check if a group of words or a single word is present in a larger string. I tried using String.contains() method but this fails in case the larger string has new line character. Currently I am using a regex mentioned below. But this works for only one word. The searched text is a user entered value and can contain more than one word. This is an android application.
String regex = ".*.{0}" + searchText + ".{0}.*";
Pattern pattern = Pattern.compile(regex);
pattern.matcher(largerString).find();
Sample String
String largerString ="John writes about this, and John writes about that," +
" and John writes about everything. ";
String searchText = "about this";
Why not just replace line breaks with spaces, and on top of that, convert it all to lower case?
String s = "hello";
String originalString = "Does this contain \n Hello?";
String formattedString = originalString.toLowerCase().replace("\n", " ");
System.out.println(formattedString.contains(s));
Edit: Thinking about it, I don't really understand how line breaks make a difference...
Edit 2: I was right. Line breaks don't matter.
String s = "hello";
String originalString = "Does this contain \nHello?";
String formattedString = originalString.toLowerCase();
System.out.println(formattedString.contains(s));
here is code not using regex.
String largerString = "John writes about this, and John writes about that," +" and John writes about everything. ";
String searchText = "about this";
Pattern pattern = Pattern.compile(searchText);
Matcher m = pattern.matcher(largerString);
if(m.find()){
System.out.println(m.group().toString());
}
Result:
about this
I hope it will help you.

Categories