I have a kmlLayer which has several placemarkers on it. I want to iterate through these placemarkers and retrieve their coordinates so as to find the distance from my location to those points and only set the markers in a certain distance visible.
I have the following code
for (KmlPlacemark placemark: layer.getPlacemarks()) {
String s = ("placemarks",placemark.getGeometry()..getGeometryObject().toString());
String s has the following format:
lat/lng: (55.94569390835889,-3.190410055779333)
I want to extract the two coordinated from it. How can I do this?
If we can guarantee that the String to parse is always defined in a canonical way, so that is defined as lat+long ALWAYS, then using regex will be the easiest way:
Example:
String latLong = "lat/lng: (55.94569390835889,-3.190410055779333)";
Pattern patte = Pattern.compile("-?[0-9]+(?:.[0-9]+)?");
Matcher matcher = patte.matcher(latLong);
while (matcher.find()) {
System.out.println(Double.parseDouble(matcher.group()));
}
So, if you don't want to use Regex, do it by hands. First remove anything before "(" and after ")"
s = s.substring(s.indexOf("(")+1,s.indexOf(")")); //this will get you "55...,-3.19..."
And then split it by ",".
String[] strngs = s.split(",");
double lat = Double.parseDouble(strings[0]);
double lon = Double.parseDouble(string[1]);
Related
String ccToken = "";
String result = "ssl_transaction_type=CCGETTOKENssl_result=0ssl_token=4366738602809990ssl_card_number=41**********9990ssl_token_response=SUCCESS";
String[] elavonResponse = result.split("=|ssl");
for (String t : elavonResponse) {
System.out.println(t);
}
ccToken = (elavonResponse[6]);
System.out.println(ccToken);
I want to be able to grab a specific part of a string and store it in a variable. The way I'm currently doing it, is by splitting the string and then storing the value of the cell into my variable. Is there a way to specify that I want to store the digits after "ssl_token="?
I want my code to be able to obtain the value of ssl_token without having to worry about changes in the string that are not related to the token since I wont have control over the string. I have searched online but I can't find answers for my specific problem or I maybe using the wrong words for searching.
You can use replaceAll with this regex .*ssl_token=(\\d+).* :
String number = result.replaceAll(".*ssl_token=(\\d+).*", "$1");
Outputs
4366738602809990
You can do it with regex. It would probably be better to change the specifications of the input string so that each key/value pair is separated by an ampersand (&) so you could split it (similar to HTTP POST parameters).
Pattern p = Pattern.compile(".*ssl_token=([0-9]+).*");
Matcher m = p.matcher(result);
if(m.matches()) {
long token = Long.parseLong(m.group(1));
System.out.println(String.format("token: [%d]", token));
} else {
System.out.println("token not found");
}
Search index of ssl_token. Create substring from that index. Convert substring to number. To number can extract number when it is at the beggining of the string.
I have been trying to drop specific values from a String holding JDBC query results and column metadata. The format of the output is:
[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]
I am trying to get it into the following format:
I_Col1=someValue1, I_Col2=someVal2, I_Col3=someVal3
I have tried just dropping everything before the "=", but some of the "someVal" data has "=" in them. Is there any efficient way to solve this issue?
below is the code I used:
for(int i = 0; i < finalResult.size(); i+=modval) {
String resulttemp = finalResult.get(i).toString();
String [] parts = resulttemp.split(",");
//below is only for
for(int z = 0; z < columnHeaders.size(); z++) {
String replaced ="";
replaced = parts[z].replace("*=", "");
System.out.println("Replaced: " + replaced);
}
}
You don't need any splitting here!
You can use replaceAll() and the power of regular expressions to simply replace all occurrences of those unwanted characters, like in:
someString.replaceAll("[\\[\\]\\{\\}", "")
When you apply that to your strings, the resulting string should exactly look like required.
You could use a regular expression to replace the square and curly brackets like this [\[\]{}]
For example:
String s = "[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]";
System.out.println(s.replaceAll("[\\[\\]{}]", ""));
That would produce the following output:
I_Col1=someValue1, I_Col2=someVal2, I_Col3=someVal3
which is what you expect in your post.
A better approach however might be to match instead of replace if you know the character set that will be in the position of 'someValue'. Then you can design a regex that will match this perticular string in such a way that no matter what seperates I_Col1=someValue1 from the rest of the String, you will be able to extract it :-)
EDIT:
With regards to the matching approach, given that the value following I_Col1= consists of characters from a-z and _ (regardless of the case) you could use this pattern: (I_Col\d=\w+),?
For example:
String s = "[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]";
Matcher m = Pattern.compile("(I_Col\\d=\\w+),?").matcher(s);
while (m.find())
System.out.println(m.group(1));
This will produce:
I_Col1=someValue1
I_Col2=someVal2
I_Col3=someVal3
You could do four calls to replaceAll on the string.
String query = "[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]"
String queryWithoutBracesAndBrackets = query.replaceAll("\\{", "").replaceAll("\\]", "").replaceAll("\\]", "").replaceAll("\\[", "")
Or you could use a regexp if you want the code to be more understandable.
String query = "[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]"
queryWithoutBracesAndBrackets = query.replaceAll("\\[|\\]|\\{|\\}", "")
I have a series of strings, each of the format :
"{3.242, 87611}, {5.658, 7.3731}, {5.547, 8.7631} ......"
Each pair of numbers in curly brackets represents one Latitude/Longitude point (and each number is of type double).
I want to parse the string so that each point in the string is represented as a separate Lat/Lon object, that I store in a list of points.
I am pretty new to Java (and parsing). I have been looking at a lot of examples but I'm still really confused as to how to even begin.
How do I go about doing this?
You can use regExp to fetch points first,
String str = "{3.242, 87611},{5.658, 7.3731}";
Pattern pattern = Pattern.compile("\\{(.*?)\\}");
Matcher match = pattern.matcher(str);
while(match.find()) {
System.out.println(match.group(1));
}
OUTPUT
3.242, 87611
5.658, 7.3731
Now you can just use split to find two points and you can parse them to Double. Note here (.*?) is a group which means any String
Assuming you have already have this String in some variable str, you can split str into it's component numbers
String[] splitNumbers = str.split("[{}, ]+");
then iterate over this list and use each pair of numbers to construct a Coordinate object.
Coordinate[] coords = new Coordinate[splitNumbers.length/2];
for(int i=0; i < splitNumbers.length-2;i+=2){
double longitude = Double.paresDouble(splitNumbers[i]);
double latitude = Double.paresDoublesplitNUmbers[i+1]);
coords[i/2] = new Coordinate(longitude,latitude);
}
I have the following expressions inside a String (that comes from a text file):
{gender=male#his#her}
{new=true#newer#older}
And I would like to:
Find the occurences of that pattern {variable=value#if_true#if_false}
Temporarily store those variables in fields such as variableName, variableValue, ifTrue, ifFalse as Strings.
Evaluate an expression based on variableName and variableValue according to local variables (like String gender = "male" and String new = "true").
And finally replace the pattern with ifTrue or ifFalse according to (3).
Should I use String.replaceAll() in some way, or how do I look for this expression and save the strings that are inside? Thanks for your help
UPDATE
It would be something like PHP's preg_match_all.
UPDATE 2
I solved this by using Pattern and Matcher as I post as an answer below.
If the strings always take this format, then string.split('#') is probably the way to go. This will return an array of strings in the '#' separator (e.g. "{gender=male#his#her}".split('#') = {"{gender=male", "his", "her}"}; use substring to remove the first and last character to get rid of the braces)
After strugling for a while I managed to get this working using Pattern and Matcher as follows:
// \{variable=value#if_true#if_false\}
Pattern pattern = Pattern.compile(Pattern.quote("\\{") + "([\\w\\s]+)=([\\w\\s]+)#([\\w\\s]+)#([\\w\\s]+)" + Pattern.quote("\\}"));
Matcher matcher = pattern.matcher(doc);
// if we'll make multiple replacements we should keep an offset
int offset = 0;
// perform the search
while (matcher.find()) {
// by default, replacement is the same expression
String replacement = matcher.group(0);
String field = matcher.group(1);
String value = matcher.group(2);
String ifTrue = matcher.group(3);
String ifFalse = matcher.group(4);
// verify if field is gender
if (field.equalsIgnoreCase("Gender")) {
replacement = value.equalsIgnoreCase("Female")?ifTrue:ifFalse;
}
// replace the string
doc = doc.substring(0, matcher.start() + offset) + replacement + doc.substring(matcher.end() + offset);
// adjust the offset
offset += replacement.length() - matcher.group(0).length();
}
Please check following code.
Pattern pxPattern = Pattern.compile("^.*[0-9]+(%|pt|em).*$");
Matcher pxMatcher = pxPattern.matcher("onehellot455emwohellothree");
System.out.println(pxMatcher.matches());
System.out.println(pxMatcher.group(0));
i want to substract string 445em. i am using code for checking css. means i wants to extract
just values like 45em or 50%.
Thanks.
First, the captured group is in group 1, not group 0. Then you need to modify your regex to not consume the numbers and include them in the group. Try:
Pattern pxPattern = Pattern.compile("^.*?([0-9]+(?:%|pt|em)).*$");
Matcher pxMatcher = pxPattern.matcher("onehellot455emwohellothree");
System.out.println(pxMatcher.matches());
System.out.println(pxMatcher.group(1));
EDIT:
To get all values from a string with several, you can use this pattern:
Pattern pxPattern = Pattern.compile("[0-9]+(?:%|pt|em)");
Matcher pxMatcher = pxPattern.matcher("margin: 0pt, 6em, 5%, 2pt");
List<String> propertyValues = new ArrayList<String>();
while (pxMatcher.find()) {
propertyValues.add(pxMatcher.group());
}