How can I convert String s="3.78 hi bye" to double c=3.78?
Same question for String s="hi 3.78 hi bye" (take only 3.78 while ignoring the text before)
You can use a regex to get rid of all characters that are not a digit or a .:
String s = "hi 3.78 hi bye";
String numberOnly = s.replaceAll("[^0-9\\.]+", "");
double d = Double.parseDouble(numberOnly); //d == 3.78d
You should add some exception handling in case the original string is not properly formatted.
you may try to use regular expression
Pattern doubleValue = Pattern.compile("\\d+\\.\\d+");
Matcher m = doubleValue.match(yourString);
if (m.find()) {
return Double.parseDouble(m.group(0));
}
return null;
Related
Here is my code:
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com\\/excludethis).*\\/"); //search for this pattern
Matcher m = p.matcher(stringToSearch); //match pattern in StringToSearch
String store= "";
// print match and store match in String Store
if (m.find())
{
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
//repeat the process
Pattern p1 = Pattern.compile("(.*)[^\\/]");
Matcher m1 = p1.matcher(store);
if (m1.find())
{
String theGroup = m1.group(0);
System.out.format("'%s'\n", theGroup);
}
I want to to match everything that is after excludethis and before a / that comes after.
With "(?<=.com\\/excludethis).*\\/" regex I will match 123456/ and store that in String store. After that with "(.*)[^\\/]" I will exclude / and get 123456.
Can I do this in one line, i.e combine these two regex? I can't figure out how to combine them.
Just like you have used a positive look behind, you can use a positive look ahead and change your regex to this,
(?<=.com/excludethis).*(?=/)
Also, in Java you don't need to escape /
Your modified code,
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern p = Pattern.compile("(?<=.com/excludethis).*(?=/)"); // search for this pattern
Matcher m = p.matcher(stringToSearch); // match pattern in StringToSearch
String store = "";
// print match and store match in String Store
if (m.find()) {
String theGroup = m.group(0);
System.out.format("'%s'\n", theGroup);
store = theGroup;
}
System.out.println("Store: " + store);
Prints,
'123456'
Store: 123456
Like you wanted to capture the value.
This may be useful for you :)
String stringToSearch = "https://example.com/excludethis123456/moretext";
Pattern pattern = Pattern.compile("excludethis([\\d\\D]+?)/");
Matcher matcher = pattern.matcher(stringToSearch);
if (matcher.find()) {
String result = matcher.group(1);
System.out.println(result);
}
If you don't want to use regex, you could just try with String::substring*
String stringToSearch = "https://example.com/excludethis123456/moretext";
String exclusion = "excludethis";
System.out.println(stringToSearch.substring(stringToSearch.indexOf(exclusion)).substring(exclusion.length(), stringToSearch.substring(stringToSearch.indexOf(exclusion)).indexOf("/")));
Output:
123456
* Definitely don't actually use this
What is the proper way to escape this String 0x\w+:0x\w+[^][]*\K\[(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)\] to be used as a Java String variable.
IntelliJ escapes this automatically into (when pasted):
String pattern = "0x\\w+:0x\\w+[^][]*\\K\\[(\\-?\\d+(\\.\\d+)?),\\s*(\\-?\\d+(\\.\\d+)?)\\]";
However, this is causing compiler error:
java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 18
\K is not valid regex. Not sure what you are trying to match with it. If you want a capitol K character, just put K
Here's what worked for me:
\[\["0x\w+:0x\w+(.+?[\d+,\d+]]])
And here's the complete code (a bit long solution):
String arrayPatternString = "\\[\\[\"0x\\w+:0x\\w+(.+?[\\d+,\\d+]]])";
Pattern arrayPattern = Pattern.compile(arrayPatternString);
Matcher arrayMatcher = arrayPattern.matcher(responseBody);
while(arrayMatcher.find()) {
String matched = arrayMatcher.group();
String g = "(\\-?\\d+(\\.\\d+)?),\\s*(\\-?\\d+(\\.\\d+)?)";
Pattern gPattern = Pattern.compile(g);
Matcher gMatcher = gPattern.matcher(matched);
while(gMatcher.find()) {
String gMatched = gMatcher.group();
String[] s = gMatched.split(",");
Double lat = Double.valueOf(s[0]);
Double lon = Double.valueOf(s[1]);
System.out.println("Lat: " + lat);
System.out.println("Lat: " + lon);
map.put("latitude", lat);
map.put("longitude", lon);
}
}
I am getting a piece of JSON text from a url connection and saving it to a string currently as such:
...//setting up url and connection
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = in.readLine();
When I print str, I correctly find the data {"build":{"version_component":"1.0.111"}}
Now I want to extract the 111 from str, but I am having some trouble.
I tried
String afterLastDot = inputLine.substring(inputLine.lastIndexOf(".") + 1);
but I end up with 111"}}
I need a solution that is generic so that if I have String str = {"build":{"version_component":"1.0.111111111"}}; the solution still works and extracts 111111111 (ie, I don't want to hard code extract the last three digits after the decimal point)
If you cannot use a JSON parser then you can this regex based extraction:
String lastNum = str.replaceAll("^.*\\.(\\d+).*", "$1");
RegEx Demo
^.* is greedy match that matches everything until last DOT and 1 or more digits that we put in group #1 to be used in replacement.
Find the start and the end indexes of the String you need and substring(start, end) :
// String str = "{"build":{"version_component":"1.0.111"}};" cannot compile without escaping
String str = "{\"build\":{\"version_component\":\"1.0.111\"}}";
int start = str.lastIndexOf(".")+1;
int end = str.lastIndexOf("\"");
String substring = str.substring(start,end);
just use JSON api
JSONObject obj = new JSONObject(str);
String versionComponent= obj.getJSONObject("build").getString("version_component");
Then just split and take the last element
versionComponent.split("\\.")[2];
Please, your can try the following code :
...
int index = inputLine.lastIndexOf(".")+1 ;
String afterLastDot = inputLine.substring(index, index+3);
With Regular Expressions (Rexp),
You can solve your problem like this ;
Pattern pattern = Pattern.compile("111") ;
Matcher matcher = pattern.matcher(str) ;
while(matcher.find()){
System.out.println(matcher.start()+" "+matcher.end());
System.out.println(str.substring(matcher.start(), matcher.end()));
}
I want to extract a perticular image path string from a given string .
The String is http:\localhost:9090\SpringMVC\images\integration-icon.png
Now i want to get only the path after images like
\images\integration-icon.png
i tried this
Pattern pattern = Pattern.compile("SpringMVC");
Matcher matcher = pattern.matcher(str);
System.out.println("Checking");
if (matcher.find()) {
System.out.println(matcher.group(1));
}
how can i get ?
String filename = filepath.substring(filepath.lastIndexOf("\\") + 1);
or (haven't tried and looks somewhat odd)
String filename = filepath.substring(filepath.lastIndexOf("\\", "images\\".length()) + 1);
String string = "http:\localhost:9090\ZenoBusinessStore\images\integration-icon.png";
int index = string.indexOf("images\\");
String output = string.substring(index);
String text = "http:\localhost:9090\SpringMVC\images\integration-icon.png"
String subText = text.subString(text.indexOf("\images"), text.length());
System.out.println(subText);
String in = "http:\\localhost:9090\\ZenoBusinessStore\\images\\integration-icon.png";
String op = in.replace("http:\\localhost:9090\\ZenoBusinessStore", "");
System.out.println(op);
ZenoBusinessStore must be the name of your project which is constant.
Now split the string
String s = "http:\localhost:9090\ZenoBusinessStore\images\integration-icon.png";
String ary = s.split("ZenoBusinessStore");
Now the 2nd element of the array is your image path.
System.out.println(ary[1]);
Use '\\'. It's because backslash is used in escape sequence like '\n'. With a single \ the compiler have no way to know.
I am trying parse out 3 pieces of information from a String.
Here is my code:
text = "H:7 E:7 P:10";
String pattern = "[HEP]:";
Pattern p = Pattern.compile(pattern);
String[] attr = p.split(text);
I would like it to return:
String[0] = "7"
String[1] = "7"
String[2] = "10"
But all I am getting is:
String[0] = ""
String[1] = "7 "
String[2] = "7 "
String[3] = "10"
Any suggestions?
A not-so-elegant solution I just devised:
String text = "H:7 E:7 P:10";
String pattern = "[HEP]:";
text = text.replaceAll(pattern, "");
String[] attr = text.split(" ");
From the javadoc, http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#split(java.lang.CharSequence) :
The array returned by this method contains each substring of the input
sequence that is terminated by another subsequence that matches this
pattern or is terminated by the end of the input sequence.
You get the empty string first because you have a match at the beginning of the string, it seems.
If I try your code with String text = "A H:7 E:7 P:10" I get indeed:
A 7 7 10
Hope it helps.
I would write a full regular expression like the following:
Pattern pattern = Pattern.compile("H:(\\d+)\\sE:(\\d+)\\sP:(\\d+)");
Matcher matcher = pattern.matcher("H:7 E:7 P:10");
if (!matcher.matches()) {
// What to do!!??
}
String hValue = matcher.group(1);
String eValue = matcher.group(2);
String pValue = matcher.group(3);
Basing on your comment I take it that you only want to get the numbers from that string (in a particular order?).
So I would recommend something like this:
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("H:7 E:7 P:10");
while(m.find()) {
System.out.println(m.group());
}