how to read string upto certain comma with java - 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

Related

Regex to find text between string pattren

String: [img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]
Result I Want: [img border=0]images/bbcode/sets/misc/bullet_go.png[/img] without /scm/ text.
Issue: Text scm is not static, could be any other text in data.
What I want: Have a look to this string
[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]
Regex which can fetch a text between ] and images/bbcode/ so the regex will detect the \scm\ text and then can remove this \scm\ from String data and end result will look like
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]
PS: I am implementing this logic in Java.
you can reach the goal without using regex, too.
since you said that the other parts are static, try this:
String myStr = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
myStr = "[img border=0]" + myStr.substring(myStr.indexOf("images"));
System.out.println(myStr);
and the output will be:
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]
I have captured text between '] and /images..' and replace this text with "". Check the following demo:
String s = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
s = s.replaceAll("(?<=])/[^/]+/","");
System.out.println(s);
if [img border=0] dynamic, you can take all except /scm/
some demo
String input = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
Pattern p = Pattern.compile("(^.*\\])\\/.*?\\/(.*$)");
Matcher m = p.matcher(input);
if (m.find()) {
String output = m.replaceFirst("$1$2");
System.out.println(output);
}
// -> [img border=0]images/bbcode/sets/misc/bullet_go.png[/img]
I found one more way to solve this same problem
String pattereString = "].*/images";
String maineString = "[img border=0]/scm/images/bbcode/sets/misc/bullet_go.png[/img]";
maineString = maineString.replaceAll(pattereString, "images");
System.out.println(maineString);
Output:
[img border=0]images/bbcode/sets/misc/bullet_go.png[/img]

Extract last number after decimal

I am getting a piece of JSON text from a url connection and saving it to a string currently as such:
...//setting up url and connection
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = in.readLine();
When I print str, I correctly find the data {"build":{"version_component":"1.0.111"}}
Now I want to extract the 111 from str, but I am having some trouble.
I tried
String afterLastDot = inputLine.substring(inputLine.lastIndexOf(".") + 1);
but I end up with 111"}}
I need a solution that is generic so that if I have String str = {"build":{"version_component":"1.0.111111111"}}; the solution still works and extracts 111111111 (ie, I don't want to hard code extract the last three digits after the decimal point)
If you cannot use a JSON parser then you can this regex based extraction:
String lastNum = str.replaceAll("^.*\\.(\\d+).*", "$1");
RegEx Demo
^.* is greedy match that matches everything until last DOT and 1 or more digits that we put in group #1 to be used in replacement.
Find the start and the end indexes of the String you need and substring(start, end) :
// String str = "{"build":{"version_component":"1.0.111"}};" cannot compile without escaping
String str = "{\"build\":{\"version_component\":\"1.0.111\"}}";
int start = str.lastIndexOf(".")+1;
int end = str.lastIndexOf("\"");
String substring = str.substring(start,end);
just use JSON api
JSONObject obj = new JSONObject(str);
String versionComponent= obj.getJSONObject("build").getString("version_component");
Then just split and take the last element
versionComponent.split("\\.")[2];
Please, your can try the following code :
...
int index = inputLine.lastIndexOf(".")+1 ;
String afterLastDot = inputLine.substring(index, index+3);
With Regular Expressions (Rexp),
You can solve your problem like this ;
Pattern pattern = Pattern.compile("111") ;
Matcher matcher = pattern.matcher(str) ;
while(matcher.find()){
System.out.println(matcher.start()+" "+matcher.end());
System.out.println(str.substring(matcher.start(), matcher.end()));
}

How to trim specific chars inside a string

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 (-:

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.

Categories