I am getting Messages from Server So that I need to Parse the Contents of the Messages.
Currently I received the Message and converted it into the String specified below,
Lat:+1290.9890N
Long:+9098.987890E
Spd:90km/h
So from the above String, I need to get the Value of Lat,Long and speed ..How to do that in Java..Thanks in advance..
There are many ways, use substring function http://docs.oracle.com/javase/6/docs/api/java/lang/String.html. Try by your self.
You can use split, substring or other ways to do it. I would recommend to use pojo for this to avoid any issues in processing string like Sting index out of bounds other possible exceptions. It will be cleaner and easier to manage as your message seems pretty static in its format.
Create a string builder for each line.
Iterate through each existing string.
Call isDigit() on each item in the string.
If isDigit == true, append the digit to the string builder.
Cast the string builder to a long
You could create a Scanner and call findInLine() with a Pattern regular expression that will only find floating point numbers e.g. (0..9)*.(0..9)*
Related
I want to make a Java program in which I want to take a String as a input. The string will have two integer numbers and operation to be performed.
eg. 25+85
or 15*78
The output will the solution of the string.
But I don't know how to split the string because operator sign is not known before execution.
You would want to check what operation it is using by using String.contains("+"); and checking all the other operators you want to support. Then split wherever that operator is, String.split("+"). From there parse the output of String.split("+") by using Integer.parseInt(String s) and then return the sum. Pretty simple, good luck.
You can use the split() method of the String class to split the input at non-digit characters:
input.split("\\D");
This will give you an array containing only the numbers.
I guess you also want to get the operator somehow? Although it's not the most elegant way, you might want to start with input.replaceAll("[^\\*\\+\\-\\/]", "") to remove everything that's not an operator, but you will still have to do some careful input filtering. What if i type 5+4*6 oder 2+hello ?
I am being given some JSON from an external process that I can't change, and I need to modify this JSON string for a downstream Java process to work. The JSON string looks like:
{"widgets":"blah","is_dog":"1"}
But it needs to look like:
{"widgets":blah,"is_dog":"1"}
I have to remove the quotes around blah. In reality, blah is a huge JSON object, and so I've simplified it for the sake of this question. So I figured I'd attack the problem by doing two String#replace calls, one before blah, and one after it:
dataString = dataString.replaceAll("{\"widgets\":\"", "{\"widgets\":");
dataString = dataString.replaceAll("\",\"is_dog\":\"1\"}", ",\"is_dog\":\"1\"}");
When I run this I get a vague runtime error:
Illegal repetition
Can any regex maestros spot where I'm going awrye? Thanks in advance.
I believe you need to escape braces. Braces are used for repetition ((foo){3} looks for foo three times in a row); hence the error.
Note: in this case it needs to be double escaping: \\{.
{ and } in regex have special meaning. They are to mention allowed repetition of patterns. So they are to be escaped here.
Use \\{\"widgets\":\"", "\\{\"widgets\": instead of {\"widgets\":\"", "{\"widgets\":.
Since the input string looks to be valid json, your best bet would be to parse it with an actual parser to a map-like structure. Regexes are not the right tools for this. Serializing this structure to to something not quite json would then be relatively simple.
I do wonder if you're better off taking the code for JSONObject and modifying the toString() method to make this a more reliable transformation than using regexps. Here's the source code, and you're looking for invocations of the quote() method
Well, why don't you simply do the following?
1) Decode the first JSON (which is correct with quotes) into varJSON1
2) Get the String "blah" in varJSON1 into varJSON2
3) Then decode the varJSON2
Hey, I've been trying to figure out why this regular expression isn't matching correctly.
List l_operators = Arrays.asList(Pattern.compile(" (\\d+)").split(rtString.trim()));
The input string is "12+22+3"
The output I get is -- [,+,+]
There's a match at the beginning of the list which shouldn't be there? I really can't see it and I could use some insight. Thanks.
Well, technically, there is an empty string in front of the first delimiter (first sequence of digits). If you had, say a line of CSV, such as abc,def,ghi and another one ,jkl,mno you would clearly want to know that the first value in the second string was the empty string. Thus the behaviour is desirable in most cases.
For your particular case, you need to deal with it manually, or refine your regular expression somehow. Like this for instance:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(rtString);
if (m.find()) {
List l_operators = Arrays.asList(p.split(rtString.substring(m.end()).trim()));
// ...
}
Ideally however, you should be using a parser for these type of strings. You can't for instance deal with parenthesis in expressions using just regular expressions.
That's the behavior of split in Java. You just have to take it (and deal with it) or use other library to split the string. I personally try to avoid split from Java.
An example of one alternative is to look at Splitter from Google Guava.
Try Guava's Splitter.
Splitter.onPattern("\\d+").omitEmptyStrings().split(rtString)
I'm trying to do some parsing in Java and I'm using Cobra HTML Parser to get the HTML into a DOM then I'm using XPath to get the nodes I want. When I get down to the desired level I call node.getTextContents(), but this gives me a string like
"\n\n\nValue\n-\nValue\n\n\n"
Is there a built in way to get rid of the line breaks? I would like to do a RegEx like
(?:\s*([^-]+)\s*-\s*([^-]+)\s*)
on the inner text and would really prefer not to have to deal with the possible different white space symbols in between the text.
Example Input:
Value
-
Value
Thanks
You can use String.replaceAll().
String trimmed = original_string.replaceAll("\n", "");
The first argument is a regular expression: you could replace all contiguous blocks of whitespace in the original string with replaceAll("\\s+", "") for instance.
I'm not totally sure I understood the question correctly, but the simplest way to remove all the whitespace would be:
String s = node.getTextContents().replaceAll("\\s","");
If you just want to get rid of the leading/trailing whitespace, use trim().
I'm not sure if the title is very clear, but basically what I have to do is read a line of text from a file and split it up into 8 different string variables. Each line will have the same 8 chunks in the same order (title, author, price, etc). So for each line of text, I want to end up with 8 strings.
The first problem is that the last two fields in the line may or may not be present, so I need to do something with stringTokenizer.hasMoreTokens, otherwise it will die messily when fields 7 and 8 are not present.
I would ideally like to do it in one while of for loop, but I'm not sure how to tell that loop what the order of the fields is going to be so it can fill all 8 (or 6) strings correctly. Please tell me there's a better way that using 8 nested if statements!
EDIT: The String.split solution seems definitely part of it, so I will use that instead of stringTokenizer. However, I'm still not sure what the best way of feeding the individual strings into the constructor. Would the best way be to have the class expecting an array, and then just do something like this in the constructor:
line[1] = isbn;
line[2] = title;
The best way is to not use a StringTokenizer at all, but use String's split method. It returns an array of Strings, and you can get the length from that.
For each line in your file you can do the following:
String[] tokens = line.split("#");
tokens will now have 6 - 8 Strings. Use tokens.length() to find out how many, then create your object from the array.
Regular expression is the way. You can convert your incoming String into an array of String using the split method
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)
Would a regular expression with capture groups work for you? You can certainly make parts of the expression optional.
An example line of data or three might be helpful.
Is this a CSV or similar file by any chance? If so, there are libraries to help you, for example Apache Commons CSV (link to alternatives on their page too). It will get you a String[] for each line in the file. Just check the array size to know what optional fields are present.