I have URLs which always end on a number, for example:
String url = "localhost:8080/myproject/reader/add/1/";
String anotherurl = "localhost:8080/myproject/actor/take/154/";
I want to extract the number between the last two slashes ("/").
Does anyone know how I can do this?
You could split the string:
String[] items = url.split("/");
String number = items[items.length-1]; //last item before the last slash
With a regular expression:
final Matcher m = Pattern.compile("/([^/]+)/$").matcher(url);
if (m.find()) System.out.println(m.group(1));
Use lastIndexOf, like this:
String url = "localhost:8080/myproject/actor/take/154/";
int start = url.lastIndexOf('/', url.length()-2);
if (start != -1) {
String s = url.substring(start+1, url.length()-1);
int n = Integer.parseInt(s);
System.out.println(n);
}
That's the basic idea. You'll have to do some error checking (for example, if a number is not found at the end of the URL), but it will work fine.
For the inputs which you specified
String url = "localhost:8080/myproject/reader/add/1/";
String anotherurl = "localhost:8080/myproject/actor/take/154/";
adding a little error handling to handle missing "/" like
String url = "localhost:8080/myproject/reader/add/1";
String anotherurl = "localhost:8080/myproject/actor/take/154";
String number = "";
if(url.endsWith("/") {
String[] urlComps = url.split("/");
number = urlComps[urlComps.length-1]; //last item before the last slash
} else {
number = url.substring(url.lastIndexOf("/")+1, url.length());
}
In One Line :
String num = (num=url.substring(0, url.length() - 1)).substring(num.lastIndexOf('/')+1,num.length());
Related
I have a string (which is an URL) in this pattern https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg
now I want to clip it to this
media/93939393hhs8.jpeg
I want to remove all the characters before the second last slash /.
i'm a newbie in java but in swift (iOS) this is how we do this:
if let url = NSURL(string:"https://xxx.kflslfsk.com/kjjfkskfjksf/v1/files/media/93939393hhs8.jpeg"), pathComponents = url.pathComponents {
let trimmedString = pathComponents.suffix(2).joinWithSeparator("/")
print(trimmedString) // "output = media/93939393hhs8.jpeg"
}
Basically, I'm removing everything from this Url expect of last 2 item and then.
I'm joining those 2 items using /.
String ret = url.substring(url.indexof("media"),url.indexof("jpg"))
Are you familiar with Regex? Try to use this Regex (explained in the link) that captures the last 2 items separated with /:
.*?\/([^\/]+?\/[^\/]+?$)
Here is the example in Java (don't forget the escaping with \\:
Pattern p = Pattern.compile("^.*?\\/([^\\/]+?\\/[^\\/]+?$)");
Matcher m = p.matcher(string);
if (m.find()) {
System.out.println(m.group(1));
}
Alternatively there is the split(..) function, however I recommend you the way above. (Finally concatenate separated strings correctly with StringBuilder).
String part[] = string.split("/");
int l = part.length;
StringBuilder sb = new StringBuilder();
String result = sb.append(part[l-2]).append("/").append(part[l-1]).toString();
Both giving the same result: media/93939393hhs8.jpeg
string result=url.substring(url.substring(0,url.lastIndexOf('/')).lastIndexOf('/'));
or
Use Split and add last 2 items
string[] arr=url.split("/");
string result= arr[arr.length-2]+"/"+arr[arr.length-1]
public static String parseUrl(String str) {
return (str.lastIndexOf("/") > 0) ? str.substring(1+(str.substring(0,str.lastIndexOf("/")).lastIndexOf("/"))) : str;
}
I have the URL
http://www.facebook.com/post/ll.html
I want to spilt the url into http://www.facebook.com/post/ and ll.html
Please help
One way of doing this is:
String myStr = "http://www.facebook.com/post/ll.html";
String strEnd = myStr.substring(myStr.lastIndexOf('/')+1);
strEnd will have the string you desire.
String x = "http://www.facebook.com/post/ll.html";
String[] splits = x.split("/");
String last = splits[splits.length - 1];
String first = x.substring(0, x.length() - last.length());
System.out.println(last); // 11.html
System.out.println(first); // http://www.facebook.com/post/
I think the best way to approach this is to also use the URL class, as there are a lot of gotchas if you just do simple string parsing. For your example:
// Get ll.html
String filePart = url.getPath().substring(url.getPath().lastIndexOf('/')+1);
// Get /post/
String pathPart = url.getPath().substring(0, url.getPath().lastIndexOf('/')+1);
// Cut off full URL at end of first /post/
pathPart = url.toString().substring(0, url.toString().indexOf(pathPart)+pathPart.length());
This will even cope with URLs like http://www.facebook.com:80/ll.html/ll.html#foo/bar?wibble=1/ll.html.
Try this:
if (null != str && str.length() > 0 )
{
int endIndex = str.lastIndexOf("/");
if (endIndex != -1)
{
String firststringurl = str.substring(0, endIndex);
String secondstringurl = str.substring(endIndex);
}
}
I can have this string as below :
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
or
String s = "chapterId=c_1§ionId=s_24666";
I need to get the number ("24666" in the examples).
String res = s.substring(s.lastIndexOf("s_")+ 2) this returns me the number + chars till the end of the string(the second example is ok). But I need to stop after the number ends. How can I do that.? Thanks
You can use regExp
String s = "chapterId=c_1§ionId=s_24666";
//OR
//String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*?s_(\\d+).*","$1");
System.out.println(s);
OUTPUT:
24666
Where,
.*?s_ means anything before s_ (s_ inclusive)
(\\d+) means one or more digits () used for group
$1 means group 1 which is digits after s_
Note:Assumed that your every string follows specific format which includes s_ and number after s_.
You can split the string by the character & to get the parameters, and split each parameter with the = to get the parameter name and parameter value. And now look for the parameter name "sectionId", and cut the first 2 characters of its value to get the number, and you can use Integer.parseInt() if you need it as an int.
Note that this solution is flexible enough to process all parameters, not just the one you're currently interested in:
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
String[] params = s.split("&");
for (String param : params) {
String[] nameValue = param.split("=");
if ("sectionId".equals(nameValue[0])) {
int number = Integer.parseInt(nameValue[1].substring(2));
System.out.println(number); // Prints 24666
// If you don't care about other parameters, this will skip the rest:
break;
}
}
Note:
You might want to put Integer.parseInt() into a try-catch block in case an invalid number would be passed from the client:
try {
int number = Integer.parseInt(nameValue[1].substring(2));
} catch (Exception e) {
// Invalid parameter value, not the expected format!
}
Try this:
I use a check in the substring() method - if there is no "&isHL" in the string (meaning its type 2 you showed us), it will just read until the string ends. otherwise, it will cut the string before the "&isHL". Hope this helps.
Code:
String s = "chapterId=c_1§ionId=s_**24666**";
int endIndex = s.indexOf("&isHL");
String answer = s.substring(s.lastIndexOf("s_") + 2, endIndex == -1 ? s.length() : endIndex);
Try following:
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
String tok[]=s.split("&");
for(String test:tok){
if(test.contains("s_")){
String next[]=test.split("s_");
System.out.println(next[1]);
}
}
Output :
24666
Alternatively you can simply remove all other words if they are not required as below
String s="chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
s=s.replaceAll(".*s_(\\d+).*","$1");
System.out.println(s);
Output :
24666
The dig over here is splitting your string using a Regular Expression to further divide the string into parts and get what is required. For more on Regular Expressions visit this link.
You could sue this regex : (?<=sectionId=s_)(\\d+) This uses positive look-behind.
demo here
Following code will work even if there is multiple occurrence of integer in given string
String inputString = "chapterId=c_a§ionId=s_24666&isHL=1&cssFileName=haynes_45";
String[] inputParams = inputString.split("&");
for (String param : inputParams)
{
String[] nameValue = param.split("=");
try {
int number = Integer.parseInt(getStringInt(nameValue[1]));
System.out.println(number);
}
catch(IllegalStateException illegalStateException){
}
}
private String getStringInt(String inputString)
{
Pattern onlyInt = Pattern.compile("\\d+");
Matcher matcher = onlyInt.matcher(inputString);
matcher.find();
String inputInt = matcher.group();
return inputInt;
}
OUTPUT
2466
1
45
Use split method as
String []result1 = s.split("&");
String result2 = tempResult[1];
String []result3 = result2.split("s_");
Now to get your desire number you just need to do
String finalResult = result3[1];
INPUT :
String s = "chapterId=c_1§ionId=s_24666&isHL=1&cssFileName=haynes";
OUPUT :
24666
EDIT :
Goal : http://localhost:8080/api/upload/form/test/test
Is it possible to have some thing like `{a-b, A-B..0-9}` kind of pattern and match them and replace with value.
i have following string
http://localhost:8080/api/upload/form/{uploadType}/{uploadName}
there can be any no of strings like {uploadType}/{uploadName}.
how to replace them with some values in java?
[Edited] Apparently you don't know what substitutions you'll be looking for, or don't have a reasonable finite Map of them. In this case:
Pattern SUBST_Patt = Pattern.compile("\\{(\\w+)\\}");
StringBuilder sb = new StringBuilder( template);
Matcher m = SUBST_Patt.matcher( sb);
int index = 0;
while (m.find( index)) {
String subst = m.group( 1);
index = m.start();
//
String replacement = "replacement"; // .. lookup Subst -> Replacement here
sb.replace( index, m.end(), replacement);
index = index + replacement.length();
}
Look, I'm really expecting a +1 now.
[Simpler approach] String.replace() is a 'simple replace' & easy to use for your purposes; if you want regexes you can use String.replaceAll().
For multiple dynamic replacements:
public String substituteStr (String template, Map<String,String> substs) {
String result = template;
for (Map.Entry<String,String> subst : substs.entrySet()) {
String pattern = "{"+subst.getKey()+"}";
result = result.replace( pattern, subst.getValue());
}
return result;
}
That's the quick & easy approach, to start with.
You can use the replace method in the following way:
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String typevalue = "typeValue";
String nameValue = "nameValue";
s = s.replace("{uploadType}",value).replace("{uploadName}",nameValue);
You can take the string that start from {uploadType} till the end.
Then you can split that string using "split" into string array.
Were the first cell(0) is the type and 1 is the name.
Solution 1 :
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/" + uploadName;
Solution 2:
String uploadName = "xyz";
String url = "http://localhost:8080/api/upload/form/{uploadName}";
url.replace("{uploadName}",uploadName );
Solution 3:
String uploadName = "xyz";
String url = String.format("http://localhost:8080/api/upload/form/ %s ", uploadName);
String s = "http://localhost:8080/api/upload/form/{uploadType}/{uploadName}";
String result = s.replace("uploadType", "UploadedType").replace("uploadName","UploadedName");
EDIT: Try this:
String r = s.substring(0 , s.indexOf("{")) + "replacement";
The UriBuilder does exactly what you need:
UriBuilder.fromPath("http://localhost:8080/api/upload/form/{uploadType}/{uploadName}").build("foo", "bar");
Results in:
http://localhost:8080/api/upload/form/foo/bar
I have strings of the form:
"abc" 1 2 1 13
"efgh" 2 5
Basically, a string in quotes followed by numbers separated by whitespace characters.
I need to extract the string and the numbers out of the line.
So for eg., for the first line, I'd want
abc to be stored in a String variable (i.e. without the quotations) and
an array of int to store [1,2,1,13].
I tried to create a pattern that'd do this, but I'm a little confused.
Pattern P = Pattern.compile("\A\".+\"(\s\d+)+");
Not sure how to proceed now. I realized that with this pattern I'd kinda be extracting the whole line out? Perhaps multiple patterns would help?
Pattern P1 = Pattern.compile("\A\".+\"");
Pattern P2 = Pattern.compile("(\s\d+)+");
Again, not very sure how to get the string and ints out of the line though. Any help is appreciated!
I would rather just split the string on space, rather than building complex regex, and use it with Pattern and Matcher class.
Something like this: -
String str = "\"abc\" 1 2 1 13 ";
String[] arrr = str.split("\\s");
System.out.println(Arrays.toString(arrr));
OUTPUT: -
["abc", 1, 2, 1, 13]
Shows your intent much clearer, that what you want to do.
Then, you can get the string and integer parts from your string array. You would need to do a Integer.parseInt() on integer elements.
If your string may contain spaces in it, then in that case, you would need a Regex. Better one would be the one in #m.buettner's answer
Use capturing groups to get both parts in one go, then split the numbers at spaces.
Pattern pattern = Pattern.compile("\"([^\"]*)\"\\s*([\\d\\s]*)");
Matcher m = pattern .matcher(input);
while (m.find()) {
String str = m.group(1);
String[] numbers = m.group(2).split("\\s");
// process both of them
}
Each set of parentheses in the regex will later correspond to one group (counting opening parentheses from left to right, starting at 1).
Please try this it will separate both String and int also
String s = "\"abc\" 1 2 1 13 ";
s = s.replace("\"", "");
String sarray[] = s.split(" ");
int i[] = new int[10];
String si[] = new String[10];
int siflag = 0;
int iflag = 0;
for (String st : sarray) {
try {
int ii = Integer.parseInt(st)
i[iflag++] = ii;
} catch (NumberFormatException e) {
si[siflag++] = st;
}
}
StringTokenizer st = new StringTokenizer(str,"\" ");
String token = null;
String strComponent = null;
int num[] = new int[10]; // can change length dynamically by using ArrayList
int i = 0;
int numTemp = -1;
while(st.hasMoreTokens()){
token = st.nextToken();
try{
numTemp = Integer.parseInt(token);
num[i++] = numTemp ;
}catch(NumberFormatException nfe){
strComponent = token.toString();
}