How to trim specific chars inside a string - java

I have this string for example:
Username: tester1tt8e677 Password: b6a492e14c
I need to get out the username and the password only.
The password and user name are dynamically changing.
What is the best way doing it with Java, and how?
Thanks.

Do yourself a massive favour and get started on regular expressions. It will take more time than blindly copy-pasting an answer, but once you grasp the concept you can solve a huge number of problems with it.
You might want to check out this tutorial, which is java-specifiy and looks quite solid. Or just go ahead and google, you will find tons of information out there.
Once again - please do learn about regular expressions. You will not regret it.

Try using a Matcher with a regex:
String pattern = "Username: (\\.+?) Password: (\\.+?)";
Matcher matcher = Pattern.compile( pattern ).matcher();
matcher.find();
You can then get your username and password from the first and second group:
String u = matcher.group(1);
String p = matcher.group(2);
However this does not sound like a good way to do whatever you are doing and you might want to consider another approach.

You could use substring:
String String1 = "Username: testter1tt8e677";
System.out.println(String1.substring(0,10));
This should return "Username:"
So:
System.out.println(String1.substring(10));
returns "testter1tt8e677".

Try with below code:
String s1 = "Username:tester1tt8e677 Password:b6a492e14c";
// splitting String
String[] splitString = s1.split(" ");
for (String sp: splitString) {
// Again Splitting
String[] s2 = sp.split(":");
System.out.println(s2[1]);
}

Rather than think of how you can work your solution around your problem, see if it can be broken up.
What do we want to do? We want to get values out of a String.
How? Rather than removing what we don't want, let's take out what we do want.
You then make the solution a lot simpler for yourself.
str = "Username: tester1tt8e677 Password: b6a492e14c";
String[] splitStrings = str.split("\\s+");
System.out.println(splitStrings[1]); //Username
System.out.println(splitStrings[3]); //Password

String str="Username: tester1tt8e677 Password: b6a492e14c";
System.out.println(str.substring(0,str.indexOf(" ", str.indexOf(" ") + 1)).split(": ")[1]);
System.out.println(str.substring(str.indexOf(" ", str.indexOf(" ") + 1)+1,str.length()).split(": ")[1]);
Output:
tester1tt8e677
b6a492e14c

Well I have found my answer and it was pretty easy:
StringBuilder pass1 = new StringBuilder(pass).delete(0, 35);
String resultString = pass1.toString();
StringBuilder user1 = new StringBuilder(user).delete(0, 10);
StringBuilder user2 = new StringBuilder(user1).delete(14, 35);
String resultString = user2.toString();
Thanks anyway (-:

Related

how to read string upto certain comma with java

i need to read a file upto certain comma,for example;
String s=hii,lol,wow,and,finally
need output as hii,lol,wow,and
Dont want last comma followed with characters
As my code is reading last comma string
Example:iam getting my code out put as: finally
Below is my code
please guide me
File file =new File("C:/Users/xyz.txt");
FileInputStream inputStream = new FileInputStream(file);
String filke = IOUtils.toString(inputStream);
String[] pieces = filke.split("(?=,)");
String answer = Arrays.stream(pieces).skip(pieces.length - 1).collect(Collectors.joining());
String www=answer.substring(1);
System.out.format("Answer = \"%s\"%n", www);
You don't necessarily need to use regex for this. Just get the index of the last ',' and get the substring from 0 to that index:
String answer = "hii,lol,wow,and,finally";
String www = answer.substring(0, answer.lastIndexOf(','));
System.out.println(www); // prints hii,lol,wow,and
String in Java has a method called lastIndexOf(String str). That might come in handy for you.
Say your input is String s = "hii,lol,wow,and,finally";
You can do a String operation like:
String s = "hii,lol,wow,and,finally";
s = s.substring(0, s.lastIndexOf(","));
This gives you the output: hii,lol,wow,and
If you want to use java 8 stream to do it for you maybe try filter ?
String answer = Arrays.stream(pieces).filter(p -> !Objects.equals(p, pieces[pieces.length-1])).collect(Collectors.joining());
this will print Answer = "hii,lol,wow,and"
To have stricly regex you can use the Pattern.compile and Matcher
Pattern.compile("\w+(?=,)");
Matcher matcher = pattern.matcher(filke);
while (matcher.find()) {
System.out.println(matcher.group(1) + ","); // regex not good enough, maybe someone can edit it to include , (comma)
}
Will match hii, lol, wow, and,
See the regex example here https://regex101.com/r/1iZDjg/1

How to get multi sub strings from String, Android/Java

I know there are similar questions regarding to this. However, I tried many solutions and it just does not work for me.
I need help to extract multiple substrings from a string:
String content = "Ben Conan General Manager 90010021 benconan#gmail.com";
Note: The content in the String may not be always in this format, it may be all jumbled up.
I want to extract the phone number and email like below:
1. 90010021
2. benconan#gmail.com
In my project, I was trying to get this result and then display it into 2 different EditText.
I have tried using pattern and matcher class but it did not work.
I can provide my codes here if requested, please help me ~
--------------------EDIT---------------------
Below is my current method which only take out the email address:
private static final String EMAIL_PATTERN =
"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\#" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+";
public String EmailValidator(String email) {
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(email);
if (matcher.find()) {
return email.substring(matcher.start(), matcher.end());
} else {
// TODO handle condition when input doesn't have an email address
}
return email;
}
You can separate your string into arraylist like this
String str = "Ben Conan, General Manager, 90010021, benconan#gmail.com";
List<String> List = Arrays.asList(str.split(" "));
maybe you should do this instead of yours :
String[] Stringnames = new String[5]
Stringnames [0] = "your phonenumber"
Stringnames[1] = "your email"
System.out.println(stringnames)
Or :
String[] Stringnames = new String[2]
String[] Stringnames = {"yournumber","your phonenumber"};
System.out.println(stringnames [1]);
String.split(...) is a java method for that.
EXAMPLE:
String content = "Ben Conan, General Manager, 90010021, benconan#gmail.com";
String[] selection = content.split(",");
System.out.println(selection[0]);
System.out.println(selection[3]);
BUT if you want to do a Regex then take a look at this:
https://stackoverflow.com/a/16053961/982161
Try this regex for phone number
[\d+]{8} ---> 8 represents number of digits in phone number
You can use
[\d+]{8,} ---> if you want the number of more than 8 digits
Use appropriate JAVA functions for matching. You can try the results here
http://regexr.com/
For email, it depends whether the format is simple or complicated. There is a good explanation here
http://www.regular-expressions.info/index.html

Showing email address as hint

I have seen Mail services displays the email id's as e*****e#gmail.com , mostly in their recovery page.
So i am trying to replace the example#gmail.com as e*****e#gmail.com .
Is it possible to achieve it using String#replace(String) alone ? or should i use some REGEX to achieve it .
Thanks for your valuable suggestions in adavance
Search regex:
\b(\w)\S*?(\S)(?=#)(\S+)\b
Replacement Pattern:
$1****$2$3****$4
RegEx Demo
Code:
String email = "anexample#gmail.com";
String repl = email.replaceFirst("\\b(\\w)\\S*?(\\S#)(\\S)\\S*(\\S\\.\\S*)\\b",
"$1****$2$3****$4");
//=> a****e#g****l.com
You can try without regex too
String email = "example#gmail.com";
int start = 1;
int end = email.indexOf("#") - 1;
StringBuilder sb = new StringBuilder(email);
StringBuilder sb1=new StringBuilder();
for(int i=start;i<end;i++){
sb1.append("*");
}
sb.replace(start, end, sb1.toString());
System.out.println(sb.toString());
Out put:
e*****e#gmail.com
It could be possible through replaceAll function.
(?<!^).(?=.*?.#)
Use the above regex and replace the matched characters with *
DEMO
String s = "example#gmail.com";
System.out.println(s.replaceAll("(?<!^).(?=.*?.#)", "*"));
Output:
e*****e#gmail.com
Update:
Use the below regex to get the output like e*****e#g***l.com
String s = "example#gmail.com";
System.out.println(s.replaceAll("\\B.\\B(?=.*?\\.)", "*"));
Output:
e*****e#g***l.com
I sugges to use indexOf and substring. With replace you can run into tuble with emails like gmail#gmail.com

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.

How to remove " " from java string

I have a java string with " " from a text file the program accesses with a Buffered Reader object. I have tried string.replaceAll(" ","") and it doesn't seem to work.
Any ideas?
cleaned = cleaned.replace(" "," ");
cleaned = cleaned.replace("\u00a0","")
This is a two step process:
strLineApp = strLineApp.replaceAll("&"+"nbsp;", " ");
strLineApp = strLineApp.replaceAll(String.valueOf((char) 160), " ");
This worked for me. Hope it helps you too!
The same way you mentioned:
String cleaned = s.replace(" "," ");
It works for me.
There's a ready solution to unescape HTML from Apache commons:
StringEscapeUtils.unescapeHtml("")
You can also escape HTML if you want:
StringEscapeUtils.escapeHtml("")
Strings are immutable so You need to do
string = string.replaceAll(" ","")
You can use JSoup library:
String date = doc.body().getElementsByClass("Datum").html().toString().replaceAll(" ","").trim();
String.replace(char, char) takes char inputs (or CharSequence inputs)
String.replaceAll(String, String) takes String inputs and matches by regular expression.
For example:
String origStr = "bat";
String newStr = str.replace('a', 'i');
// Now:
// origStr = "bat"
// newStr = "bit"
The key point is that the return value contains the new edited String. The original String variable that invokes replace()/replaceAll() doesn't have its contents changed.
For example:
String origStr = "how are you?";
String newStr = origStr.replaceAll(" "," ");
String anotherStr = origStr.replaceAll(" ","");
// origStr = "how are you?"
// newStr = "how are you?"
// anotherStr = howareyou?"
We can have a regular expression check and replace HTML nbsp;
input.replaceAll("[\\s\\u00A0]+$", "") + "");
It removes non breaking spaces in the input string.
My solution is the following, and only this worked for me:
String string = stringWithNbsp.replaceAll("NNBSP", "");
Strings in Java are immutable. You have to do:
String newStr = cleaned.replaceAll(" ", "");
I encountered the same problem: The inner HTML of the element I needed had "&nbsp" and my assertion failed.
Since the question has not accepted any answer,yet I would suggest the following, which worked for me
String string = stringwithNbsp.replaceAll("\n", "");
P.S : Happy testing :)

Categories