What's the simplest way of changing the w= number and h= number?
Example of url:
https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop
I have to dynamically change bolded parts.
I can extract the value of w like this:
s = s.substring(s.indexOf("=") + 1, s.indexOf("&"));
But how could I change it?
I tried searching Stackoverflow, but couldn't find anything.
Thanks.
If i understood correctly you are trying to replace the values after the = sign for h and w.
You can simply do that with RegEx as follows:
"https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop"
.replaceAll("w=\\d+", "w=NEW_VALUE").replaceAll("&h=\\d+", "&h=NEW_VALUE")
What is happening above is that we first find the patern that matches w=AnyNumberHere and we replace the entire section with w=NEW_VALUE. Likewise we replace &h=AnyNumberHere with &h=NEW_VALUE
This solution is not length depended, therefore if the URL has a variable length this will still work, and will even work if the value h=123 or w=1234 for example do not exist ;)
In your case you can use String replaceAll method. Example of use:
String string =
"https://test.com/photos/226109/test-photo-226109." +
"jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop";
String replacedString = string
.replaceAll(string.substring(string.indexOf("=") + 1,
string.indexOf("&")), "1000");
When you get your numbers from string you can convert it to StringBuffer.
Like this
String s = new String("https://test.com/photos/226109/test-photo-226109.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb&fit=crop");
StringBuffer sb = new StringBuffer(s);
sb.replace(s.indexOf("w=") + 2, s.indexOf("&"), "2000");
sb.replace(s.indexOf("h=") + 2, s.indexOf("&"), "2000");
s = sb.toString();
Related
Need help with getting rid of half of a string in android studio. The string is:
final String strOrigin = String.valueOf(origin).trim();
The value that is returned is;
"Point{type=Point, bbox=null, coordinates=[27.993726079654873,-26.14686805145815]}"
I want to be left with only the numbers of that, in the String. I have tried;
strOrigin.replace("Point{type=Point, bbox=null, coordinates=", "");
But it isn't working. Any help would be appreciated.
In Java strings are immutable. You must assign the result to a new string:
String strResult = strOrigin.replace("Point{type=Point, bbox=null, coordinates=", "");
Make your life simpler by just getting the coordinates:
final String strOigin = origin.coordinates().stream()
.map(String::valueOf)
.collect(Collectors.joining(",","{","}"));
Or, if you're stuck on java 7:
final String strOigin = String.format(
"{%s,%s}",
String.valueOf(origin.latitude()),
String.valueOf(origin.longitude())
);
Maybe you forgot that replace() returns the result and you must assign it to a string:
String strOrigin = "Point{type=Point, bbox=null, coordinates=[27.993726079654873,-26.14686805145815]}";
String str = strOrigin
.replace("Point{type=Point, bbox=null, coordinates=", "")
.replace("}","");
System.out.println(str);
will print:
[27.993726079654873,-26.14686805145815]
This should do the trick
String s="blabla coordinates=[27.993726079654873,-26.14686805145815] ";
String requiredString = s.substring(s.indexOf("[") + 1, s.indexOf("]"));
will print:
27.993726079654873,-26.14686805145815
Than you can cast it to double or latlong format
Have a look at regular expressions, they allow you to define more flexible search patterns. In your example you only find the coordinates if the rest of the string matches the pattern exactly, but if you happen to get some other value of bbox, or even extra space it will not work. This will always match everything between a pair of square brackets:
String c = origin.replaceAll(".+?(\\[.+?\\]).+?", "$1");
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
I'm using JAVA and I have a string called example that looks like;
example = " id":"abcd1234-efghi5678""tag":"abc" "
NOTE: I have't escaped the "'s using \ but you get the idea..
...I want to just return;
abcd1234
...I've been trying using substring
example = (example.substring(example.lastIndexOf("id\":\"")+5));
(because this string could be anywhere in a HTML/JSON File) which kinda works all the lastIndexOf does is find it and then keep everything AFTER it - i.e it returns;
abcd1234-efghi5678""tag":"abc"
Basically I need to find the lastIndexOf based on the string and limit it returns afterwards - I found that I could do it another substring command like this;
example = (example.substring(example.lastIndexOf("id\":\"")+5));
example = example.substring(0,8);
...but it seems messy. Is there any way of using lastIndexOf and also setting a max length at the same time - it's probably something really simple that I can't see due to staring at it for so long.
Many thanks in advance for your help!
Don't substring twice. Use the found index twice instead:
int idx = example.lastIndexOf("id\":\"");
example = example.substring(idx + 5, idx + 13);
Or, if the length is dynamic, but always ends with -:
int start = example.lastIndexOf("id\":\"");
int end = example.indexOf('-', start);
example = example.substring(start + 5, end);
In real code, you should of course always check that the substring is found at all, i.e. that idx / start / end are not -1.
You can use a regex to find the specific substring:
String regex = "^id[^a-z0-9]+([a-zA-Z0-9]+)-.*$";
Matcher p = Pattern.compile(regex).matcher(example);
String result = null;
if (p.matches()) {
result = p.group(1);
}
System.out.println(result); //outputs exactly "abcd1234"
The pattern uses a capturing group that matches id followed by non-alphanumeric characters and preceding -.
I have a string :
"id=40114662&mode=Edit&reminderId=44195234"
All i want from this string is the final number 44195234. I can't use :
String reminderIdFin = reminderId.substring(reminderId.lastIndexOf("reminderId=")+1);
as i cant have the = sign as the point it splits the string. Is there any other way ?
Try String.split(),
reminderIdFin.split("=")[3];
You can use indexOf() method to get where this part starts:
int index = reminderIdFin.indexOf("Id=") + 3;
the plus 3 will make it so that it jumps over these characters. Then you can use substring to pull out your wanted string:
String newString = reminderIdFin.substring(index);
Remove everything else and you'll be left with your target content:
String reminderIdFin = reminderId.replaceAll(".*=", "");
The regex matches everything up to the last = (the .* is "greedy").
How can I substring a string if I have to search for a specific word in a string first which will become the start point of substring?
For example, I have a url like this http://www.youtube.com/get_video_info?html5=1&video_id=fn45T6k5JzA&cpn=SS3mhNaZwOE7WnYl&ps=native&el=embedded&hl=en_US&sts=15956&width=500&height=400&c=web&cver=html5 and I need to substring video ID from it.
You can try regular expressions
Here's some information on using regular expressions in java
The following regular expression:
video_id=(.*?)&
should do it.
http://rubular.com/r/d24wDwk2wv
To answer the title explicitly:
s = s.substring(s.indexOf("word") + "word".length());
Use this:
String url="http://www.youtube.com/get_video_info?html5=1&video_id=fn45T6k5JzA&cpn=SS3mhNaZwOE7WnYl&ps=native&el=embedded&hl=en_US&sts=15956&width=500&height=400&c=web&cver=html5";
String subData=url.substring(url.indexOf("video_id=")+"video_id=".length(),url.indexOf("&",url.indexOf("video_id="))); // outputs fn45T6k5JzA
Have a look at different variations string#indexOf method here.
In this case you would use String.indexOf(String toIndex) and this will give the index of the first character in the substring. If you do:
String video = "http://www.youtube.com/get_video_info?html5=1&video_id=fn45T6k5JzA&cpn=SS3mhNaZwOE7WnYl&ps=native&el=embedded&hl=en_US&sts=15956&width=500&height=400&c=web&cver=html5";
String data = video.substring(video.indexOf("video_id=") + 9);
This should give you what you're looking for.
You can use substring from between posithon after video_id= and its next &
String link = "http://www.youtube.com/get_video_info?html5=1&video_id=fn45T6k5JzA&cpn=SS3mhNaZwOE7WnYl&ps=native&el=embedded&hl=en_US&sts=15956&width=500&height=400&c=web&cver=html5";
int start = link.indexOf("video_id") + "video_id".length() + 1; // +1 to include position of `=`
int end = link.indexOf("&", start);
String value = link.substring(start, end);
System.out.println(value);
output: fn45T6k5JzA
Other, probably more readable way would be using URLEncodedUtils from Apache HttpComponents
String link = "http://www.youtube.com/get_video_info?html5=1&video_id=fn45T6k5JzA&cpn=SS3mhNaZwOE7WnYl&ps=native&el=embedded&hl=en_US&sts=15956&width=500&height=400&c=web&cver=html5";
List<NameValuePair> parameters = URLEncodedUtils.parse(link,
Charset.forName("UTF-8"));
for (NameValuePair nvp : parameters) {
if (nvp.getName().equals("video_id"))
System.out.println(nvp.getValue());
}
output: fn45T6k5JzA
I am trying to parse the certain name from the filename.
The examples of File names are
xs_1234323_00_32
sf_12345233_99_12
fs_01923122_12_12
I used String parsedname= child.getName().substring(4.9) to get the 1234323 out of the first line. Instead, how do I format it for the above 3 to output only the middle numbers(between the two _)? Something using split?
one line solution
String n = str.replaceAll("\\D+(\\d+).+", "$1");
most efficent solution
int i = str.indexOf('_');
int j = str.indexOf('_', i + 1);
String n = str.substring(i + 1, j);
String [] tokens = filename.split("_");
/* xs_1234323_00_32 would be
[0]=>xs [1]=> 1234323 [2]=> 00 [3] => 32
*/
String middleNumber = tokens[2];
You can try using split using the '_' delimiter.
The String.split methods splits this string around matches of the given ;parameter. So use like this
String[] output = input.split("_");
here output[1] will be your desired result
ANd input will be like
String input = "xs_1234323_00_32"
I would do this:
filename.split("_", 3)[1]
The second argument of split indicates the maximum number of pieces the string should be split into, in your case you only need 3. This will be faster than using the single-argument version of split, which will continue splitting on the delimiter unnecessarily.