Regex: extract float data from String and group it - java

i have a string like this one:
288.999,224.004 283.665,258.338 313.332,293.005 312.332,336.671 270.999,389.338 371.998,412.338
i try to parse the data to float values, but i want to sort it! The value before comma should by my x value and the value after comma should be the y value.
Pattern p = Pattern.compile("[0-9]+.[0-9]*");
Matcher m = p.matcher(pointString);
while(m.find())
{
System.out.print("x:"+m.group(0)); //x- Values
// System.out.print("y:"+m.group(1)); //y- Values
}
This code just creates a single group...How should i change my String pattern to get a second group with the y-Values...
favored result:
x:288.999
y:224.004
x:283.665
y:258.338
....

Keep it simple, split is enough:
String input = "288.999,224.004 283.665,258.338 313.332,293.005 312.332,336.671 270.999,389.338 371.998,412.338";
String[] points = input.split(" ");
for (String point : points) {
String[] coordinates = point.split(",");
System.out.println("x:" + coordinates[0]);
System.out.println("y:" + coordinates[1]);
}

The pattern you are looking for:
((?:\\d*\\.\\d+)|(?:\\d+\\.\\d*)) *, *((?:\\d*\\.\\d+)|(?:\\d+\\.\\d*))
also, group(0) would bring the whole match, you're rather looking for group(1) and group(2)

This will work
String str = "288.999,224.004 283.665,258.338 313.332,293.005 312.332,336.671 270.999,389.338 371.998,412.338";
String[] points=str.split(" ");
String[] point=new String[2];
for(int i=0;i<points.length;i++){
point=points[i].split(",");
System.out.println("X-val: "+point[0]);
System.out.println("Y-val: "+point[1]);
}

Related

JAVA Get text from String

Hi I get this String from server :
id_not="autoincrement"; id_obj="-"; id_tr="-"; id_pgo="-"; typ_not=""; tresc="Nie wystawił"; datetime="-"; lon="-"; lat="-";
I need to create a new String e.x String word and send a value which I get from String tresc="Nie wystawił"
Like #Jan suggest in comment you can use regex for example :
String str = "id_not=\"autoincrement\"; id_obj=\"-\"; id_tr=\"-\"; id_pgo=\"-\"; typ_not=\"\"; tresc=\"Nie wystawił\"; datetime=\"-\"; lon=\"-\"; lat=\"-\";";
Pattern p = Pattern.compile("tresc(.*?);");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group());
}
Output
tresc="Nie wystawił";
If you want to get only the value of tresc you can use :
Pattern p = Pattern.compile("tresc=\"(.*?)\";");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println(m.group(1));
}
Output
Nie wystawił
Something along the lines of
Pattern p = Pattern.compile("tresc=\"([^\"]+)\");
Matcher m = p.matcher(stringFromServer);
if(m.find()) {
String whatYouWereLookingfor = m.group(1);
}
should to the trick. JSON parsing might be much better in the long run if you need additional values
Your question is unclear but i think you get a string from server and from that string you want the string/value for tresc. You can first search for tresc in the string you get. like:
serverString.substring(serverString.indexOf("tresc") + x , serverString.length());
Here replace x with 'how much further you want to pick characters.
Read on substring and delimiters
As values are separated by semicolon so annother solution could be:
int delimiter = serverstring.indexOf(";");
//in string thus giving you the index of where it is in the string
// Now delimiter can be -1, if lets say the string had no ";" at all in it i.e. no ";" is not found.
//check and account for it.
if (delimiter != -1)
String subString= serverstring.substring(5 , iend);
Here 5 means tresc is on number five in string, so it will five you tresc part.
You can then use it anyway you want.

Check if id in string and get value if so

I am trying to get a regex to match, then get the value with it. For example, I want to check for 1234 as an id and if present, get the status (which is 0 in this case). Basically its id:status. Here is what I am trying:
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
if (topicStatus.matches(regex)) {
//How to get status?
}
Not only do I not know how to get the status without splitting and looping through, I don't know why it doesn't match the regex.
Any help would be appreciated. Thanks.
Use the Pattern class
String topicStatus = "1234:0,567:1,89:2";
String someId = "1234";
String regex = "\\b"+someId+":[0-2]\\b";
Pattern MY_PATTERN = Pattern.compile(regex);
Matcher m = MY_PATTERN.matcher(topicStatus);
while (m.find()) {
String s = m.group(1);
System.out.println(s);
}
The key here is to surround the position you want [0-2] in parenthesis which means it will be saved as the first group. You then access it through group(1)
I made some assumptions that your pairs we're always comma separate and then delimited by a colon. Using that I just used split.
String[] idsToCheck = topicStatus.split(",");
for(String idPair : idsToCheck)
{
String[] idPairArray = idPair.split(":");
if(idPairArray[0].equals(someId))
{
System.out.println("id : " + idPairArray[0]);
System.out.println("status: " + idPairArray[1]);
}
}

Building a pattern to extract data out of a string

I have strings of the form:
"abc" 1 2 1 13
"efgh" 2 5
Basically, a string in quotes followed by numbers separated by whitespace characters.
I need to extract the string and the numbers out of the line.
So for eg., for the first line, I'd want
abc to be stored in a String variable (i.e. without the quotations) and
an array of int to store [1,2,1,13].
I tried to create a pattern that'd do this, but I'm a little confused.
Pattern P = Pattern.compile("\A\".+\"(\s\d+)+");
Not sure how to proceed now. I realized that with this pattern I'd kinda be extracting the whole line out? Perhaps multiple patterns would help?
Pattern P1 = Pattern.compile("\A\".+\"");
Pattern P2 = Pattern.compile("(\s\d+)+");
Again, not very sure how to get the string and ints out of the line though. Any help is appreciated!
I would rather just split the string on space, rather than building complex regex, and use it with Pattern and Matcher class.
Something like this: -
String str = "\"abc\" 1 2 1 13 ";
String[] arrr = str.split("\\s");
System.out.println(Arrays.toString(arrr));
OUTPUT: -
["abc", 1, 2, 1, 13]
Shows your intent much clearer, that what you want to do.
Then, you can get the string and integer parts from your string array. You would need to do a Integer.parseInt() on integer elements.
If your string may contain spaces in it, then in that case, you would need a Regex. Better one would be the one in #m.buettner's answer
Use capturing groups to get both parts in one go, then split the numbers at spaces.
Pattern pattern = Pattern.compile("\"([^\"]*)\"\\s*([\\d\\s]*)");
Matcher m = pattern .matcher(input);
while (m.find()) {
String str = m.group(1);
String[] numbers = m.group(2).split("\\s");
// process both of them
}
Each set of parentheses in the regex will later correspond to one group (counting opening parentheses from left to right, starting at 1).
Please try this it will separate both String and int also
String s = "\"abc\" 1 2 1 13 ";
s = s.replace("\"", "");
String sarray[] = s.split(" ");
int i[] = new int[10];
String si[] = new String[10];
int siflag = 0;
int iflag = 0;
for (String st : sarray) {
try {
int ii = Integer.parseInt(st)
i[iflag++] = ii;
} catch (NumberFormatException e) {
si[siflag++] = st;
}
}
StringTokenizer st = new StringTokenizer(str,"\" ");
String token = null;
String strComponent = null;
int num[] = new int[10]; // can change length dynamically by using ArrayList
int i = 0;
int numTemp = -1;
while(st.hasMoreTokens()){
token = st.nextToken();
try{
numTemp = Integer.parseInt(token);
num[i++] = numTemp ;
}catch(NumberFormatException nfe){
strComponent = token.toString();
}

Substring to remove everything before first period and after second

So I have a filename that looks like this:
myFile.12345.txt
If I wanted to end up with just the "12345" how would I go about removing that from the filename if the 12345 could be anywhere between 1 and 5 numbers in length?
If you are sure that there would be 2 periods . for sure
String fileName = string.split("\\.")[1]
you can use this
String s="ghgj.7657676.jklj";
String p = s.substring(s.indexOf(".")+1,s.lastIndexOf("."));
Assuming you want to extract all the numbers, you could use a simple regex to remove all the non-digits characters:
String s = "myFile.12345.txt";
String numbers = s.replaceAll("[^\\d]","");
System.out.println(numbers); //12345
Note: It would not work with file12.12345.txt for example
static final Pattern P = Pattern.compile("^(.*?)\\.(.*?)\\.(.*?)$");
...
...
...
Matcher m = P.matcher(input);
if (m.matches()) {
//String first = m.group(1);
String middle = m.group(2);
//String last = m.group(3);
...
}

Convert string to array in Java?

I have a string which has the values like this (format is the same):
name:xxx
occupation:yyy
phone:zzz
I want to convert this into an array and get the occupation value using indexes.
Any suggestions?
Basically you would use Java's split() function:
String str = "Name:Glenn Occupation:Code_Monkey";
String[] temp = str.split(" ");
String[] name = temp[0].split(":");
String[] occupation = temp[1].split(":");
The resultant values would be:
name[0] - Name
name[1] - Glenn
occupation[0] - Occupation
occupation[1] - Code_Monkey
Read about Split functnio. You can split your text by " " and then by ":"
I would recommend using String's split function.
Sounds like you want to convert to a property Map rather than an array.
e.g.
String text = "name:xxx occupation:yyy phone:zzz";
Map<String, String> properties = new LinkedHashMap<String, String>();
for(String keyValue: text.trim().split(" +")) {
String[] parts = keyValue.split(":", 2);
properties.put(parts[0], parts[1]);
}
String name = properties.get("name"); // equals xxx
This approach allows your values to be in any order. If a key is missing, the get() will return null.
If you are only interested in the occupation value, you could do:
String s = "name:xxx occupation:yyy phone:zzz";
Pattern pattern = Pattern.compile(".*occupation:(\\S+).*");
Matcher matcher = pattern.matcher(s);
if (matcher.matches()){
String occupation = matcher.group(1);
}
str = "name:xxx occupation:yyy phone:zzz
name:xx1 occupation:yy3 phone:zz3
name:xx2 occupation:yy1 phone:zz2"
name[0] = str.subtsring(str.indexAt("name:")+"name:".length,str.length-str.indexAt("occupation:"))
occupation[0] = str.subtsring(str.indexAt("occupation:"),str.length-str.indexAt("phone:"))
phone[0] = str.subtsring(str.indexAt("phone:"),str.length-str.indexAt("occupation:"))
I got the solution:
String[] temp= objValue.split("\n");
String[] temp1 = temp[1].split(":");
String Value = temp1[1].toString();
System.out.println(value);

Categories

Resources