How to filter string in java - java

I have the following string in Java. For Example:
String abc = "nama=john; class=6; height=170; weight=70";
How can I extract the value of height from the String?
Outputs: height=170
This is the code I have written so far:
String abc = "nama=john; class=6; height=170; weight=70";
String[] tokens = abc.split("; ");
List<String> listString = new ArrayList<String>();
String mod = new String();
for (String s : tokens) {
mod = s;
System.out.println(s);
listString.add(mod);
}
System.out.println(listString.size());
But I do not get the value height. Instead, I get value of height as a String.
Thanks.

With this Code-Snippet:
String abc = "nama=john; class=6; height=170; weight=70";
for(String sa : abc.split(";")){
System.out.println(sa.trim());
}
you generate this output:
nama=john
class=6
height=170
weight=70
if you want to add a specific String into a list you put the sa.trim() at the List.add parameter. To find the height-String you can use:
if(sa.trim().startsWith("height")) and you have the needed String.

you can use this regex:
(?<=height=)(\d+)(?=;|\Z)
if you want to implement this, you can do it like this:
Pattern pattern = Pattern.compile("(?<=height=)(\\d+)(?=;|\\Z)");
// create matcher object.
Matcher m = pattern.matcher(abc);
if (m.find())
{
String height = m.group(0);
}
else
{
System.out.println("not found");
}
here, you have an example: https://regex101.com/r/iM3gY0/2
and here you have an executable snipped: https://ideone.com/azngNt
If you want all parameter, you can use this regex:
(\w+)=([\d|\w]+)(?=;|\"|\Z)
so you get as Pattern:
Pattern pattern = Pattern.compile("(\\w+)=([\d|\\w]+)(?=;|\\"|\\Z)");
and the Regex101 again: https://regex101.com/r/uT6uK1/3

#Fast Snail you are correct, but I think they wanted an integer value of it:
final String string = "nama=john; class=6; height=170; weight=70";
final String[] tokens = string.split("; ");
for (String token : tokens) {
if (token.contains("height")) {
System.out.println(token);
final String[] heightSplit = token.split("=");
Integer heightValue = new Integer(heightSplit[1]);
System.out.println("height=" + heightValue);
}
}
System.out.println(tokens.length);
This should do what you need.

Use String tokenizer
import java.util.StringTokenizer;
public class stringval {
StringTokenizer st = new StringTokenizer(" nama=john, class=6, height=170, weight=70;",",");{
while(st.hasMoreTokens()){
String abc=st.nextToken();
if(abc.equals("height=170")){
StringTokenizer s=new StringTokenizer(abc,"=");
while(s.hasMoreTokens()){
String str=s.nextToken();
if (s.equals("170")){
System.out.print(s);
break;
}
}
}
}
}
}

With Java 8 you can do the following:
Map<String, String> map = Arrays.stream("nama=john; class=6; height=170; weight=70".split(";"))
.map(s -> s.trim().split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
System.out.println(map.get("height")); //170

Thanks Mr. MrT.
Code answer: Resolved.
String abc = "nama=john; class=6; height=170; weight=70";
String[] tokens = abc.split("; ");
List<String> listString = new ArrayList<String>();
String mod = new String();
for(String s:tokens){
mod =s;
System.out.println(s);
listString.add(mod);
}
System.out.println(listString.size());
for(String abcd :listString){
if(abcd.trim().startsWith("height")){
System.out.println(abcd);
}
}

Related

Extracting a substring from a given string pattern

Here are the Strings:
Example 1 - Movie=HULK/Incredible HULK;old_actor=Edward Norton;new_actor=Mark Ruffalo
Example 2 - Movie=HULK/Incredible HULK;old_movie_release_date=12 December 2008;new_movie_release_date=20 June 2012
How can I extract values like old_actor, new actor from example 1 and new_movie_release_date and old_movie_release_date from example 2.
I'm new to regex trying to see how can this be done. Thanks in advance.
You can do using java regex as follows
String str1 = "Movie=HULK/Incredible HULK;old_actor=Edward Norton;new_actor=Mark Ruffalo";
String str2 = "Movie=HULK/Incredible HULK;old_movie_release_date=12 December 2008;new_movie_release_date=20 June 2012";
String pattern1="Movie=(.*?);old_actor=(.*?);new_actor=(.*?)$";
String pattern2="Movie=(.*?);old_movie_release_date=(.*?);new_movie_release_date=(.*?)$";
Matcher m1 = Pattern.compile(pattern1).matcher(str1);
if (m1.find()) {
System.out.println("old_actor: " + m1.group(2));
System.out.println("new_actor: " + m1.group(3));
}
Matcher m2 = Pattern.compile(pattern2).matcher(str2);
if (m2.find()) {
System.out.println("old_movie_release_date: " + m2.group(2));
System.out.println("new_movie_release_date: " + m2.group(3));
}
You could use String.split(String regex).
First, you use String.split(";"), which will give you an array String[] values with contents looking like Movie=moviename, then you use String.split("=") on each string in the first array
for(String str : values) {
String[] keyValue = str.split("=");
}
to create subarrays of length 2 with key at position 0 and value at position 1.
Just an enhancement to #DerLebkuchenmann's solution
public static void main(String[] args) {
String str1 = "Movie=HULK/Incredible HULK;old_actor=Edward Norton;new_actor=Mark Ruffalo";
String str2 = "Movie=HULK/Incredible HULK;old_movie_release_date=12 December 2008;new_movie_release_date=20 June 2012";
Map<String, String> props1 = getProps(str1);
Map<String, String> props2 = getProps(str2);
System.out.println(String.format("Old Actor: %s", props1.get("old_actor")));
System.out.println(String.format("Old Movie Release Date: %s", props2.get("old_movie_release_date")));
System.out.println(String.format("New Movie Release Date: %s", props2.get("new_movie_release_date")));
}
private static Map<String, String> getProps(String str1) {
return Arrays.stream(str1.split(";"))
.map(pair -> pair.split("="))
.collect(Collectors.toMap(crumbs -> crumbs[0], crumbs -> crumbs[1]));
}
Another approach using StringTokenizer and assembling a HashMap for result:
public class Main
{
public static void main(String[] args) {
HashMap<String,String> m = new HashMap<String,String>();
StringTokenizer st = new StringTokenizer("Movie=HULK/Incredible HULK;old_actor=Edward Norton;new_actor=Mark Ruffalo",";=");
while(st.hasMoreTokens()) {
String s = st.nextToken();
if (st.hasMoreTokens()) { // ensure well-formed
m.put(s,st.nextToken());
}
}
System.out.println(m);
}
}
Prints:
{Movie=HULK/Incredible HULK, old_actor=Edward Norton, new_actor=Mark Ruffalo}

Extract Substring from String java

I want to extract specific substrings from a string:
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+
"info2 info2ContentA";
The result should be:
String info1 ="info1ContentA info1ContentB";
String info2 ="info2ContentA";
String info3 ="info3ContentA info3ContentB";
For me it's very difficult to extract the informations, because sometimes after "info" their are one, two or more content informations. Another problem that occurs is, that the order of info1, info2 etc. is not sorted and the "real data" doesn't contain a ascending number.
My first idea was to add info1, info2, info3 etc to an ArrayList.
private ArrayList<String> arr = new ArrayList<String>();
arr.add("info1");
arr.add("info2");
arr.add("info3");
Now I want to extract the substring with the method StringUtils.substringBetween() from Apache Commons (https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.4):
String result = StringUtils.substringBetween(source, arr.get(0), arr.get(1));
This works, if info1 is in the string before info2, but like I said the "real data" is not sorted.
Any idea how I can fix this?
Split those string by space and then use String's method startsWith to add the part to proper result string
Map<String, String> resultMap = new HashMap<String, String>();
String[] prefixes = new String[]{"info1", "info2", "info3"};
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB"+" info2 info2ContentA";
String[] parts = source.split(" ");
for(String part : parts) {
for(String prefix : prefixes) {
if(part.startsWith(prefix) {
String currentResult = (resultMap.containsKey(prefix) ? resultMap.get(prefix) + part + " " : part);
resultMap.put(prefix, currentResult);
}
}
}
Also consider using StringBuilder instead of adding string parts
If you cannot be sure that parts will be embraces with spaces you can change at the beginning all part to <SPACE>part in your source string using String replace method
You can use a regular expression, like this:
String source = "info1 info1ContentA info1ContentB info3 info3ContentA info3ContentB info2 info2ContentA";
for (int i = 1; i < 3; i++) {
Pattern pattern = Pattern.compile("info" + i + "Content[A-Z]");
Matcher matcher = pattern.matcher(source);
List<String> matches = new ArrayList<>();
while (matcher.find()) {
matches.add(matcher.group());
}
// process the matches list
}

Android: split a string considering 2 separating characters

I have a string containing messages. The string looks like this:
bill:hello;tom:hi;bill:how are you?;tommy:hello!; ...
I need to split the string into several srings, on the characters : and ;.
For now, I have split the string on ; and i could add the results in list elements.
List<Message> listMessages = new ArrayList<Message>();
StringTokenizer tokenizer = new StringTokenizer(messages, ";");
String result = null;
String uname = "";
String umess = "";
while (tokenizer.hasMoreTokens()) {
result = tokenizer.nextToken();
listMessages.add(new Message(result, ""));
}
I still have to do this on the : to have the two resulting strings in my list element, and I tried something like that:
List<Message> listMessages = new ArrayList<Message>();
StringTokenizer tokenizer = new StringTokenizer(messages, ";");
String result = null;
String uname = "";
String umess = "";
while (tokenizer.hasMoreTokens()) {
result = tokenizer.nextToken().split(":");
uname = result[0];
umess = result[1];
listMessages.add(new Message(result[0], result[1]));
}
But I got this error, that I don't understand?
01-23 17:12:19.168: E/AndroidRuntime(711): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.appandroid/com.example.appandroid.ListActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
Thanks in advance to look at my problem.
Instead of using StringTokenizer, you can use String.split(regex) to split based on two delimiters like below:
String test="this: bill:hello;tom:hi;bill:how are you?;tommy:hello!;";
String[] arr = test.split("[:;]");
for(String s: arr){
System.out.println(s);
}
Output:
this
bill
hello
tom
hi
bill
how are you?
tommy
hello!
EDIT:
from #njzk2 comments if you just wanna use StringTokenizer you can use one of its overloaded constructor which takes 2 args .
StringTokenizer str = new StringTokenizer(test, ":;");

java regular expression

I have a string like this
STAR=20110209
00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209
00:01:01|STRT=20110209
00:01:01|STOP=20110209 00:01:01|
and i want to extract values of few of the keys here.
like whats the value of PNAM and SSTA.
I want a regular expression that can provide the values of few of the keys and keys can be in any order.
Would something like this work for you?
String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01";
String[] parts = str.split("\\|");
for (String part : parts)
{
String[] nameValue = part.split("=");
if (nameValue[0] == "somekey")
{
// ..
}
}
So, the way your problem is really isn't best solved with regular expressions. Instead, use split() like someone else has offered, but instead of having a crazy if loop, load everything into a map.
String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01";
String[] parts = str.split("|");
Map<String, String> properties = new HashMap<String, String>();
for (String part : parts) {
String[] nameValue = part.split("=");
properties.put(nameValue[0], nameValue[1]);
}
Then all you have to do is, properties.get("PNUM")
Use this Java code:
String str = "STAR=20110209 00:01:01|PNAM=test_.xml|PNUM=480|SSTA=20110209 00:01:01|STRT=20110209 00:01:01|STOP=20110209 00:01:01|";
Pattern p = Pattern.compile("([^=]*)=([^|]*)\\|");
Matcher m = p.matcher(str);
String pnamVal = null, sstaVal = null;
while (m.find()) {
//System.out.println("Matched: " + m.group(1) + '=' + m.group(2));
if (m.group(1).equals("PNAM"))
pnamVal = m.group(2);
else if (m.group(1).equals("SSTA"))
sstaVal = m.group(2);
if (pnamVal != null && sstaVal != null)
break;
}
System.out.println("SSTA: " + sstaVal);
System.out.println("PNAM: " + pnamVal);
OUTPUT
SSTA: 20110209 00:01:01
PNAM: test_.xml

How to parse this string in Java?

prefix/dir1/dir2/dir3/dir4/..
How to parse the dir1, dir2 values out of the above string in Java?
The prefix here can be:
/usr/local/apache2/resumes
If you want to split the String at the / character, the String.split method will work:
For example:
String s = "prefix/dir1/dir2/dir3/dir4";
String[] tokens = s.split("/");
for (String t : tokens)
System.out.println(t);
Output
prefix
dir1
dir2
dir3
dir4
Edit
Case with a / in the prefix, and we know what the prefix is:
String s = "slash/prefix/dir1/dir2/dir3/dir4";
String prefix = "slash/prefix/";
String noPrefixStr = s.substring(s.indexOf(prefix) + prefix.length());
String[] tokens = noPrefixStr.split("/");
for (String t : tokens)
System.out.println(t);
The substring without the prefix "slash/prefix/" is made by the substring method. That String is then run through split.
Output:
dir1
dir2
dir3
dir4
Edit again
If this String is actually dealing with file paths, using the File class is probably more preferable than using string manipulations. Classes like File which already take into account all the intricacies of dealing with file paths is going to be more robust.
...
String str = "bla!/bla/bla/"
String parts[] = str.split("/");
//To get fist "bla!"
String dir1 = parts[0];
In this case, why not use new File("prefix/dir1/dir2/dir3/dir4") and go from there?
String str = "/usr/local/apache/resumes/dir1/dir2";
String prefix = "/usr/local/apache/resumes/";
if( str.startsWith(prefix) ) {
str = str.substring(0, prefix.length);
String parts[] = str.split("/");
// dir1=parts[0];
// dir2=parts[1];
} else {
// It doesn't start with your prefix
}
String result;
String str = "/usr/local/apache2/resumes/dir1/dir2/dir3/dir4";
String regex ="(dir)+[\\d]";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
result = matcher.group();
System.out.println(result);
}
output--
dir1
dir2
dir3
dir4
Using String.split method will surely work as told in other answers here.
Also, StringTokenizer class can be used to to parse the String using / as the delimiter.
import java.util.StringTokenizer;
public class Test
{
public static void main(String []args)
{
String s = "prefix/dir1/dir2/dir3/dir4/..";
StringTokenizer tokenizer = new StringTokenizer(s, "/");
String dir1 = tokenizer.nextToken();
String dir2 = tokenizer.nextToken();
System.out.println("Dir 1 : "+dir1);
System.out.println("Dir 2 : " + dir2);
}
}
Gives the output as :
Dir 1 : prefix
Dir 2 : dir1
Here you can find more about StringTokenizer.
If it's a File, you can get the parts by creating an instanceof File and then ask for its segments.
This is good because it'll work regardless of the direction of the slashes; it's platform independent (except for the "drive letters" in windows...)
public class Test {
public static void main(String args[]) {
String s = "pre/fix/dir1/dir2/dir3/dir4/..";
String prefix = "pre/fix";
String[] tokens = s.substring(prefix.length()).split("/");
for (int i=0; i<tokens.length; i++) {
System.out.println(tokens[i]);
}
}
}
String.split(String regex) is convenient but if you don't need the regular expression handling then go with the substring(..) example, java.util.StringTokenizer or use Apache commons lang 1. The performance difference when not using regular expressions can be a gain of 1 to 2 orders of magnitude in speed.
String s = "prefix/dir1/dir2/dir3/dir4"
String parts[] = s.split("/");
System.out.println(s[0]); // "prefix"
System.out.println(s[1]); // "dir1"
...

Categories