Concatenating url in jsp - java

I want to concatenate url with the value of string variable.
Example
string filename="example"
string extention="txt"
<a href="myuploads/(value of filename).(value of extention)">
How can I do that ?

String filename = "example"
String extension = "txt"
String url = "myuploads/" + filename + "." + extension
I the JSP :
<a href='<%= url%>'></a>

Instead of declaring another variable it can be done like this as well :
Usage of unnecessary variables must be curbed whenever and wherever applicable .

Related

Remove non numeric characters in a filename except in the extension in java

I'm trying to convert a file into a String and after that i will replace the name of the converted file without non numeric characters but when i replace it the file extension of the file is also replaced. for example (2014.05-06.txt -> 20140506.txt but whats happening is 20140506txt) i want to remain the .txt, .log or any type of extension.
String strDatefiles = Arrays.toString(saDateFiles).replaceAll("[\\W]", "");
Edited:
String[] saDateFiles = fileList.list();
String strDatefiles = Arrays.toString(saDateFiles.substring(0, saDateFiles.lastIndexOf("."))).replaceAll("[\\W]", "");
this saDateFiles.lastIndexOf("."))) have error replace with a length?
Edited2:
String[] saDateFiles = fileList.list();
String strDatefiles = Arrays.toString(saDateFiles).substring(0, Arrays.toString(saDateFiles).lastIndexOf(".")).replaceAll("[\\W]","");
System.out.println(strDatefiles);`
Output: 20140502txt20140904 (I have 2 files inside)
I would take the indexOf the last . in the String, and then manipulate the two substrings. For example,
String saDateFiles = "2014.05-06.txt";
int lastDot = saDateFiles.lastIndexOf('.');
String strDatefiles = saDateFiles.substring(0, lastDot).replaceAll("\\D", "")
.concat(saDateFiles.substring(lastDot));
System.out.println(strDatefiles);
Outputs (as requested)
20140506.txt
As you noticed, the above was for one file name. To do it for an array of file names, you could use a for-each loop and the above code like
String[] saDateFilesArr = fileList.list();
for (String saDateFiles : saDateFilesArr) {
int lastDot = saDateFiles.lastIndexOf('.');
String strDatefiles = saDateFiles.substring(0, lastDot)
.replaceAll("\\D", "").concat(saDateFiles.substring(lastDot));
System.out.println(strDatefiles);
}
Apply your replace function to the part of file name before the ".". You can extract this part with the code :
fileName.substring(0, fileName.lastIndexOf(".")) ;
Use :
String strDatefiles = Arrays.toString(saDateFiles.substring(0, saDateFiles.lastIndexOf("."))).replaceAll("[\\W]", "");

Create a Java String variable with string formatting

I need to create a String variable . that should be like following variable.
String search = "xmlns="http://tempuri.org/" />";
but I cannot assign xmlns="http://tempuri.org/" /> directly into a String variable because tempuri.org/" />"; get commented automatically.
I need a format this string and finally variable should be like this
search = xmlns="http://tempuri.org/" /> ;
How can I achieve this ?
You need to use escape characters:
String search = "xmlns=\"http://tempuri.org/\" />";
Version from the comments:
String search = "xmlns=\"tempuri.org/\"; /></soap:Body>";
You have to escape the special chars i.e replace the " for \"
String search = "xmlns=\"http://tempuri.org/\" />";

Java : how to get text between "http://" and first following "/" occurence ? And after first "/" occurence?

I am still a novice with regular expressions, "regex", etc... in Java.
If I have an url like this : "http://somedomain.someextention/somefolder/.../someotherfolder/somepage"
What is the simplest way to get :
"somedomain.someextention" ?
"somefolder/.../someotherfolder/somepage" ?
"somepage" ?
Thanks !
You don't have to (and probably shouldn't) use regex here. Instead use classes defined to handle things like this. You can use for example URL, URI, File classes like
String address = "http://somedomain.someextention/somefolder/.../someotherfolder/somepage";
URL url = new URL(address);
File file = new File(url.getPath());
System.out.println(url.getHost());
System.out.println(url.getPath());
System.out.println(file.getName());
Outpit:
somedomain.someextention
/somefolder/.../someotherfolder/somepage
somepage
Now you can need to get rid of / at start of path to your resource. You can use substring(1) here if resource starts with /.
But if you really must use regex you can try with
^https?://([^/]+)/(.*/([^/]+))$
Now
group 1 will contain host name,
group 2 will contain path to resource
group 3 will contain name of resource
The best way to get those components is to use the URI class; e.g.
URI uri = new URI(str);
String domain = uri.getHost();
String path = uri.getPath();
int pos = path.lastIndex("/");
...
// or use File to parse the path string.
You could do it using regexes on the raw url string, but there is a risk that you won't correctly cope with all of the variability that is possible in a URL. (Hint: the regex supplied by #Pchenko doesn't :-)) And you would definitely need to use a decoder to deal with possible percent encoding.
This is not a regexp or URI use but simple substring code as an excersise material. Missing few corner case format validation.
int lastDelim = str.lastIndexOf('/);
if (lastDelim<0) throw new IllegalArgumentException("Invalid url");
int startIdx = str.indexOf("//");
startIdx = startIdx<0 ? 0 : startIdx+2;
int pathDelim = str.indexOf('/', startIdx);
String domain = str.substring(startIdx, pathDelim);
String path = str.substring(pathDelim+1, lastDelim);
String page = str.substring(lastDelim+1);
If you would like to use regex to decode the URL instead of using the URI class, as described in the previous answers, the below link gives a nice tutorial of regex, and it explains decoding a sample URL as well. You could learn it there and try it out.
http://www.beedub.com/book/2nd/regexp.doc.html
It's not regex, or scalable at that, it works though:
public class SomeClass
{
public static void main(String[] args)
{
SomeClass sclass = new SomeClass();
String[] string =
sclass.parseURL("http://somedomain.someextention/somefolder/.../someotherfolder/somepage");
System.out.println(string[0]);
System.out.println(string[1]);
System.out.println(string[2]);
}
private String[] parseURL(String url)
{
String part1 = url.substring("http://".length(), url.indexOf("/", "http://".length()));
String part2 = url.substring("http://".length() + part1.length() + 1, url.lastIndexOf("/"));
String part3 = url = url.substring(url.lastIndexOf("/") + 1);
return new String[] { part1, part2, part3 };
}
}
Output:
somedomain.someextention
somefolder/.../someotherfolder
somepage

java regex get just the filename

need some help on pattern mathcing; I need to extract just the filename from a string like:
https://www.testsite.com/files/form/anonymous/api/library/ecb198be-1f05-4b0b-b0cd-7d878488a8c4/document/050cc508-1ea6-4b5f-a22b-b3edbdf6291f/media/x.jpg
just the x.jpg part
& also from this string:
<img alt="/JAGC/Images?action=AttachFile&do=get&target=Images/x.jpg">
& if they are the same image, then replace the target with the URL string.
I can regex out the the
any help please?
It doesn't need any regexp.
Use like this:
String code = "...";
String filename = code.substring(code.lastIndexOf("/")+1, code.length());
Edit:
And in the second case, you dont need the ending of the tag, so use code.length()-2
It's as simple as this:
String filename1 = url.replaceAll(".*/([^/]+)", "$1");
String filename2 = xml.replaceAll(".*/([^\"]+)\".*", "$1");
if (filename1.equals(filename2))
xml = xml.replaceAll("(.*/)([^\"]+)(\".*)", "$1" + url + "$3");
Try this:
str.replaceAll("^.*([a-z]+\\.[a-z]+).*$","$1");
The () group the filename to $1.

I think I'm missing something here -- string.replace()

I have the code
String txt = "<p style=\"margin-top: 0\">";
txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
In a for loop (which is what the i is for), but when I run this, nothing gets replaced. Am I using this wrong?
It should look like this:
String txt = "<p style=\"margin-top: 0\">";
txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
"String" is an immutable type, which means that methods on a String do not change the String itself. More info here - http://en.wikipedia.org/wiki/Immutable_object.
The replace method does not modify the string on which it is called but instead returns the reference to the modified string.
If you want txt to refer to the modified string you can do:
txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
If you want txt to continue to refer to the original string and want a different reference to refer to the changed string you can do:
String new_txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
String is a immutable class, which means instance methods of a String object don't alter the string itself. You have to gather the return value of those instance methods.

Categories