I have this xml node. I want to split the coordinate to latitude and longitude using java.
<MAP>1234:3.12345,119.12345</MAP>
I want to split the coordinate or at least can get the coordinate with this format (lat,long). Thanks all.
Have you tried with regex ?
final Pattern regex = Pattern.compile("<MAP>((.*):(.*),(.*))</MAP>", Pattern.DOTALL);
final Matcher matcher = regex.matcher(whatyouwanttoparselatlongwiththeaboveformat);
if (matcher.find()) {
System.out.print(matcher.group(2) + " : (lat,lon) = ");
float latitude = Float.valueOf(matcher.group(3));
float longitude = Float.valueOf(matcher.group(4));
System.out.println(latitude + "," + longitude);
}
Then you can deal with latitude and longitude as you wish.
Related
I've been making an mobile android application on android studio and I've got locations saved on the database. I need to convert these long and lats into a double so that it can be used in a google maps fragment.
At the moment it is getting the string from the database like this:
Cursor res = dbHelper3.getEvent(journey, message);
if (res.getCount() == 0) {
showMessageData("Error", "No data");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append(res.getString(1));
}
but theres an issue with converting it into a double as both long and lat are saved as one big string. For example it will print:
"52.301293 0.185935"
When I try this
String location = buffer.toString();
locationText.setText(buffer.toString().trim());
float f = Float.parseFloat(location);
it gives an error:
This cannot be converted into a double as its two separate numbers Is there a way of somehow separating these into two double numbers or do I have to redesign the way my database gets the location ?
You are trying to convert a string containing space into double, which will ultimately crash app.
You need to split your string ''location'' to two strings by space as:
String[] splited = location.split("\\s+");
Then you can covert it to double as below
double latitude = Double.parseDouble(splited[0]);
double longitude = Double.parseDouble(splited[1]);
You need to keep the latitude and longitude information separately like that:
String location = "52.301293 0.185935";
String[] afterSplitLoc = location.split(" ");
After that convert them to Double like that :
double latitude = Double.parseDouble(afterSplitLoc[0]);
double longitude = Double.parseDouble(afterSplitLoc[1]);
And than use on map. For example add a marker:
private GoogleMap googleMap((MapView)rootView.findViewById(R.id.YOURMAPID)).getMap();
googleMap.addMarker(new MarkerOptions().position(new LatLng( latitude, -longitude)).title("Marker"));
IMO, unless you have special reason, you should save the latitude and longitude in separate columns, as it will make future update operation easier.
You can use split() method to separate the two values:
String location = "52.301293 0.185935";
String[] latlng = location.split(" ");
System.out.println("Lat = " +latlng[0]+" Longitude = "+latlng[1]);
//You will get sth like "Lat = 52.301293 Longitude = 0.185935"
Just use something like this:
String location = buffer.toString().trim();
String[] latLon = location.split(" ");
double lat = Double.parseDouble(latLon[0]);
double lon = Double.parseDouble(latLon[1]);
thanks kshetline,
worked perfect
String string = buffer.toString();
String[] parts = string.split(" ");
String part1 = parts[0]; // 004
String part2 = parts[1]; // 034556
locationText.setText(part1 + "\n" + part2);
float longNum = Float.parseFloat(part1);
float latNum = Float.parseFloat(part2);
locationText.setText(longNum + "\n" + latNum);
final LatLng eventLocation1 = new LatLng(longNum, latNum);
let's say i have string like that:
eXamPLestring>1.67>>ReSTOfString
my task is to extract only 1.67 from string above.
I assume regex will be usefull, but i can't figure out how to write propper expression.
If you want to extract all Int's and Float's from a String, you can follow my solution:
private ArrayList<String> parseIntsAndFloats(String raw) {
ArrayList<String> listBuffer = new ArrayList<String>();
Pattern p = Pattern.compile("[0-9]*\\.?[0-9]+");
Matcher m = p.matcher(raw);
while (m.find()) {
listBuffer.add(m.group());
}
return listBuffer;
}
If you want to parse also negative values you can add [-]? to the pattern like this:
Pattern p = Pattern.compile("[-]?[0-9]*\\.?[0-9]+");
And if you also want to set , as a separator you can add ,? to the pattern like this:
Pattern p = Pattern.compile("[-]?[0-9]*\\.?,?[0-9]+");
.
To test the patterns you can use this online tool: http://gskinner.com/RegExr/
Note: For this tool remember to unescape if you are trying my examples (you just need to take off one of the \)
You could try matching the digits using a regular expression
\\d+\\.\\d+
This could look something like
Pattern p = Pattern.compile("\\d+\\.\\d+");
Matcher m = p.matcher("eXamPLestring>1.67>>ReSTOfString");
while (m.find()) {
Float.parseFloat(m.group());
}
Here's how to do it in one line,
String f = input.replaceAll(".*?(-?[\\d.]+)?.*", "$1");
Which returns a blank String if there is no float found.
If you actually want a float, you can do it in one line:
float f = Float.parseFloat(input.replaceAll(".*?(-?[\\d.]+).*", "$1"));
but since a blank cannot be parsed as a float, you would have to do it in two steps - testing if the string is blank before parsing - if it's possible for there to be no float.
String s = "eXamPLestring>1.67>>ReSTOfString>>0.99>>ahgf>>.9>>>123>>>2323.12";
Pattern p = Pattern.compile("\\d*\\.\\d+");
Matcher m = p.matcher(s);
while(m.find()){
System.out.println(">> "+ m.group());
}
Gives only floats
>> 1.67
>> 0.99
>> .9
>> 2323.12
You can use the regex \d*\.?,?\d* This will work for floats like 1.0 and 1,0
Have a look at this link, they also explain a few things that you need to keep in mind when building such a regex.
[-+]?[0-9]*\.?[0-9]+
example code:
String[] strings = new String[3];
strings[0] = "eXamPLestring>1.67>>ReSTOfString";
strings[1] = "eXamPLestring>0.57>>ReSTOfString";
strings[2] = "eXamPLestring>2547.758>>ReSTOfString";
Pattern pattern = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+");
for (String string : strings)
{
Matcher matcher = pattern.matcher(string);
while(matcher.find()){
System.out.println("# float value: " + matcher.group());
}
}
output:
# float value: 1.67
# float value: 0.57
# float value: 2547.758
/**
* Extracts the first number out of a text.
* Works for 1.000,1 and also for 1,000.1 returning 1000.1 (1000 plus 1 decimal).
* When only a , or a . is used it is assumed as the float separator.
*
* #param sample The sample text.
*
* #return A float representation of the number.
*/
static public Float extractFloat(String sample) {
Pattern pattern = Pattern.compile("[\\d.,]+");
Matcher matcher = pattern.matcher(sample);
if (!matcher.find()) {
return null;
}
String floatStr = matcher.group();
if (floatStr.matches("\\d+,+\\d+")) {
floatStr = floatStr.replaceAll(",+", ".");
} else if (floatStr.matches("\\d+\\.+\\d+")) {
floatStr = floatStr.replaceAll("\\.\\.+", ".");
} else if (floatStr.matches("(\\d+\\.+)+\\d+(,+\\d+)?")) {
floatStr = floatStr.replaceAll("\\.+", "").replaceAll(",+", ".");
} else if (floatStr.matches("(\\d+,+)+\\d+(.+\\d+)?")) {
floatStr = floatStr.replaceAll(",", "").replaceAll("\\.\\.+", ".");
}
try {
return new Float(floatStr);
} catch (NumberFormatException ex) {
throw new AssertionError("Unexpected non float text: " + floatStr);
}
}
I need to extract the values after :70: in the following text file using RegEx. Value may contain line breaks as well.
My current solution is to extract the string between :70: and : but this always returns only one match, the whole text between the first :70: and last :.
:32B:xxx,
:59:yyy
something
:70:ACK1
ACK2
:21:something
:71A:something
:23E:something
value
:70:ACK2
ACK3
:71A:something
How can I achive this using Java? Ideally I want to iterate through all values, i.e.
ACK1\nACK2,
ACK2\nACK3
Thanks :)
Edit: What I'm doing right now,
Pattern pattern = Pattern.compile("(?<=:70:)(.*)(?=\n)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
System.out.println(matcher.group())
}
Try this.
String data = ""
+ ":32B:xxx,\n"
+ ":59:yyy\n"
+ "something\n"
+ ":70:ACK1\n"
+ "ACK2\n"
+ ":21:something\n"
+ ":71A:something\n"
+ ":23E:something\n"
+ "value\n"
+ ":70:ACK2\n"
+ "ACK3\n"
+ ":71A:something\n";
Pattern pattern = Pattern.compile(":70:(.*?)\\s*:", Pattern.DOTALL);
Matcher matcher = pattern.matcher(data);
while (matcher.find())
System.out.println("found="+ matcher.group(1));
result:
found=ACK1
ACK2
found=ACK2
ACK3
You need a loop to do this.
Pattern p = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = p.matches(input);
while (m.find()) {
list.add(m.group());
}
As seen here Create array of regex matches
String Total = driver.findElement(By.xpath("wwwww")).getText();
I will get the Value £232.69 from the above code. Now I want to split the separate the Value without that Currency Symbol. Like 232.69.
So that I can compare this value with another one.
This will give you any first number (integer or not, matching expression someNumbers + optional(dot + someNumbers)) occuring in string s as a string:
String s = "&21.37";
Pattern p = Pattern.compile("[^0-9]*([0-9]+(\\.[0-9]*)?)");
Matcher m = p.matcher(s);
m.matches();
String s = m.group(1)
You can then extract it as follows:
Double d = Double.valueOf(s)
Here is updated code: , #kripindas
String s = "&1,221.37";
Pattern p = Pattern.compile("[^0-9]*([0-9]*,?([0-9]+(\\.[0-9]*))?)");
Matcher m = p.matcher(s);
m.matches();
String s_num = m.group(1).replace(",", "");
System.out.println(s_num);
Double d_num = Double.valueOf(s_num);
System.out.println(d_num);
Note that this will match:
"&1,234.56", "$123,4.5678", "JP234,123.12"
and convert them to (correspondingly):
1234.56
1234.5678
234123.12
you can use the .substring() js function for doing this. you can get more details from http://www.w3schools.com/jsref/jsref_substring.asp
use th following
String Total = driver.findElement(By.xpath("wwwww")).getText().substring(1);
I figured this out a few minutes ago.
price = driver.find_element_by_css_selector("div.teaser-pricing div.pricing").text
print(price.split()[0].replace('$', ''))
This will split it from the first index and replace what you want from the text in the second part.
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]);
}