Parsing a string using regex [duplicate] - java

This question already has answers here:
How do I get the file name from a String containing the Absolute file path?
(13 answers)
Closed 7 years ago.
I'm trying to slpit the string /home/user/test.dat
I use String[] split = file.split("(?!.*/)"); but split[1] only returns the first character instead of the whole file name. How would I edit my regex so that it returns everything past the last forward slash?

Unless there's some compelling reason to use a regular expression, I would use the simple String.lastIndexOf(int). Something like,
String file = "/a/b/c/d/e/test.dat";
int afterSlash = file.lastIndexOf('/');
if (afterSlash > -1) {
file = file.substring(afterSlash + 1);
}
System.out.println(file);
Output of above being (the requested)
test.dat

Regex
\/((\w+)\.(\w+))$
Debuggex Demo
However, since you are using Java simply load the string into the File helper which can pull out the filename:
Java
Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();

Related

Grabbing partial data from URL in Selenium [duplicate]

This question already has answers here:
Parse a URI String into Name-Value Collection
(30 answers)
Closed 4 years ago.
In selenium, is there a way to grab partial dynamically changing data from a URL? Example, I ran driver.getCurrentUrl() in my code and retrieved the below URL. I only want to grab the numeric portion of it and concatenate it so I end up with 819499-1. However, next time I run it the values will be different. Is there a way to capture this information without capturing the entire URL?
http://custmaint/clnt_estimate_overview.jsp?estimateNbr=819499&versionNbr=1&estimateMgmt=true&clntAutoAssign=true
I think this is a more generic question, not only related to Selenium...
Basically, You could use regular expression matching like so:
String url = "http://custmaint/clnt_estimate_overview.jsp?estimateNbr=819499&versionNbr=1&estimateMgmt=true&clntAutoAssign=true";
final Pattern p = Pattern.compile("^.*\\?estimateNbr=(\\d+)&versionNbr=(\\d+).*$");
Matcher m = p.matcher(url);
if (m.find()) {
System.out.print(m.group(1) + "-" + m.group(2));
}
Another approach (more flexible) is to use a dedicated library like httpcomponents; see How to convert map to url query string?
String url = driver.getCurrentUrl();
String estimateNbr = url.substring(url.indexOf("eNbr=")+5, url.indexOf("&v"));
String versionNbr = url.substring(url.indexOf("nNbr=")+5, url.indexOf("&e"));
System.out.println(estimateNbr + "-" + versionNbr);

How to get only filename without .mp3 and .mp4 extension in android?

I have audio and video names like this :
- azan1(1).mp3
- Funny.mp4
So I need an only AudioName as azan and VideoName as Funny. I am newbie in android and don't know how can I get only filename? How can I achieve this in code.??
Try this way to get filename without extension:-
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
In Java , simple and efficient way to get the filename
String resultName= filename.split("\\.")[0].split("\\(")[0];
As mentioned by 44kksharma, you can split the String at the . to get the extension. The only problem as I can see is if the file name contains . elsewhere (for an instance filename.test.mp3) - the file is an mp3 but one could argue filename.test is a part of the file name. If you think of it like that, this is the right approach using splitting:
String resultName = filename.split("\\.mp")[0];
If you have other extensions, you can do this:
String resultName = filename.split("\\.mp|\\.wav|\\.otherformat")[0];
mp3 and mp4 with have mp in them, therefore files with either extension is guaranteed to have .mp.
Using | is or in regex.
Alternatively, you can use the replaceAll method:
String result = filename.replaceAll("\\.mp3|\\.mp4", "");
replace works too, but as it doesn't use regex I find it ends up replacing the wrong chars or ends up screwing up the replacement.
Finally, you could use substring too, but using one-liners is possible with regex(/non-regex using replace) with split(), replace() and replaceAll()
if(audioname.contions(.mp3)
{
String audiostr= audioname.replace(".mp3", "");
}
if(videoname.contions(.mp4)
{
String videostr= videoname.replace(".mp3", "");
}
Set the String in your required textview

How to replace String with different slashes? [duplicate]

This question already has answers here:
java split function
(6 answers)
Closed 7 years ago.
I need to rename some paths in database.
I rename folder:
String mainFolder= "D:\test\1\data"; //folder renamed from fd
Then i need to rename all files and directories inside that folder:
String file1="D:\test\1\fd\dr.jpg";
String folder1="D:\test\1\fd\fd"; // in this case last fd needs to be renamed
String folder2="src/fd/fd/"; //fake path also needs to be renamed
What is the best and fastest way to rename that strings?
My thoughts about "/":
String folder2= "src/da/da";
String[] splittedFakePath = folder2.split("/");
splittedFakePath[splittedFakePath.length - 2] = "data";
StringBuffer newFakePath = new StringBuffer();
for (String str : splittedFakePath) {
newFakePath.append(str).append("/");
}
String after rename: src/data/da/
But when im trying split by "\":
Arrays.toString(Pattern.compile(File.separator).split(folder1));
I receive:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
Look into java's String replace(...) method.
It is wonderful for string replacement, much better than attempting a regex.
Keep in mind that real directory handling has a few special cases, which don't lend themselves well to direct string manipulation. For example '//' often gets compacted to '/' in Unix like systems, and if you care about proper directory corner-cases, then use the Java Path class

How to add symbol " to a String? [duplicate]

This question already has answers here:
Quotation marks inside a string [duplicate]
(4 answers)
Closed 8 years ago.
Is it possible to add this symbol " to a String or print to console?
I'm using it for my ImageIcon! file path thanks!
Yes, you need to escape the character with \ for Java to understand it:
String quote = "\"";
To be able to include " in a Java String you need to escape it like this
String s = "this is a String containing \" which is escaped by backslash"
Another way that was not mentioned here is the use of a char object.
String quote1 = (char)'"';
String quote2 = (char)34;
Did you mean How to print "Hello World" text on console? If yes then you can do that like this:
System.out.print("\"Hello World\"");
String str="Prashant"+"*^%$##!\" ";
you need to add before it the Escape character .

How do I manipulate strings with regex?

I'm fairly new to java and I'm trying to get a part of a string:
Say I have a URL and I want a specific part of it, such as a filename:
String url = "http://example.com/filename02563.zip";
The 02563 will be generated at random every time and it's now always 5 characters long.
I want to have java find what's between "m/" (from .com/) to the end of the line to get the filename alone.
Now consider this example:
Say I have an html file that I want a snippet extracted from. Below would be the extracted example:
<applet name=someApplet id=game width="100%" height="100%" archive=someJarFile0456799.jar code=classInsideAJarFile.class mayscript>
I want to extract the jar filename, so I want to get the text between "ve=" and ".jar". The extension will always be ".jar", so including this is not important.
How would I do this? If possible, could you comment the code so I understand what's happening?
Use the Java URI class where you can access the individual elements.
URI uri = new URI("http://example.com/filename02563.zip");
String filename = uri.getPath();
Granted, this will need a little more work if the resource no longer resides in the root path.
You can use the lastIndexOf() and substring() methods from the String class to extract a specific piece of a String:
String url = "http://example.com/filename02563.zip";
String filename = url.substring(url.lastIndexOf("/") + 1); //+1 skips ahead of the '/'
You have answers for your first question so this is for second one. Normally I would use some XML parser but your example is not valid XML file so this will be solved with regex (as you wanted).
String url = "<applet name=someApplet id=game width=\"100%\" height=\"100%\" archive=someJarFile0456799.jar code=classInsideAJarFile.class mayscript>";
Pattern pattern= Pattern.compile("(?<=archive=).*?(?= )");
Matcher m=pattern.matcher(url);
if(m.find())
System.out.println(m.group());
output:
someJarFile0456799.jar

Categories