So I have an initial file set:
file1.txt
file2.txt
When I make a change to these files and save them, I append a time stamp to them, so they'd become:
fileN_DD-Mon-YYYY_HHMMSS.txt
But if I was to make any additional saves, the timestamps would begin stacking:
fileN_DD-Mon-YYYY_HHMMSS_DD-Mon-YYYY_HHMMSS.txt
I need a way to get the substring that occurs before the first occurrence of either "." or "_" to get the string that is before them (i.e., actual file name ("fileN")).
I've gotten to this point with
int lastDot = fileName.getName().lastIndexOf('.');
String renamed = fileName.getName().substring(0,lastDot) + getDateTime() + fileName.getName().substring(lastDot);
I've tried using Scanner::useDelimiter to get the first occurrance of a "." or "_" using regexes but no luck.
String renamed = savedFileName(fileName)
public static String savedFileName(String fileName) {
final String TXT = ".txt";
Scanner s = new Scanner(fileName);
s.useDelimiter(<regex>);
String trueFileName = s.next();
s.close();
return trueFileName + getDateTime() + TXT;
for the regex, I've tried "\\W", but that returns just the latest timestamp:
_DD-Mon-YYYY_HHMMSS.txt
, and ".|_" but that returns this monstrosity:
fileN.txt_DD-Mon-YYYY.txt_(more timestamps).txt.
You can use String's split method with regex pattern \.|_:
String longFile = "fileN_DD-Mon-YYYY_HHMMSS.txt";
String shortFile = "file1.txt ";
String pattern = "\\.|_"; // need to escape backslash
System.out.println(longFile.split(pattern)[0]);
System.out.println(shortFile.split(pattern)[0]);
Or, equivalently, regex [._].
Output:
fileN
file1
Related
If I have a string like :
String str = "startDate:23/04/2016;endDate:;renewDate;"
Required multiple operation on the string.I need to get a String and extract different sub-strings using a delimiter (";") then again extract different sub-strings to form a key-value using a delimiter (":"). If against the key their is no value present the update with diff-diff default value like ("01/01/2000","01/01/1900" since both are of type Date).
if you notice for renewDate field their is no separator (":") in this case we need to append the separator along with default value (:01/01/1900) so that my expected result would be like :
String str = "startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;"
I have tried below regex but it is not working for all scenario :
String regExpression = "(?<=\\bendDate:)[;]+"
str = str.replaceAll(regExpression , "01/01/2000");
Can any one guide me how to achive the result using regex.Thanks!!!!!
As Tim said we can use regex pattern to replace the value. Adding to his answer, the only change I recommend to add colon(:) as optional in pattern used for both renewDate and endDate in text.
String endDate = "01/01/2000";
String renewDate = "01/01/1900";
String str = "startDate:23/04/2016;endDate:;renewDate;";
str = str.replaceAll(";endDate:?;", ";endDate:"+endDate+";");
str = str.replaceAll(";renewDate:?;", ";renewDate:"+renewDate+";");
System.out.println(str);
This will give the output as below
startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;
Using a regex replacement, we can try:
String endDate = "01/01/2000";
String renewDate = "01/01/1900";
String str = "startDate:23/04/2016;endDate:;renewDate:;";
String output = str.replaceAll("\\bendDate:;", "endDate:" + endDate + ";")
.replaceAll("\\brenewDate:;", "renewDate:" + renewDate + ";");
System.out.println(output);
This prints:
startDate:23/04/2016;endDate:01/01/2000;renewDate:01/01/1900;
The logic here is to only target empty end and renew date fields, including default values if needed.
Alternatively, separate strings based on your first delimiter ; and then :.
String str = "startDate:23/04/2016;endDate:;renewDate;";
String dates[] = str.split(";");
for(String date : dates){
String default[] = date.split(":");
output.append(default[0] + ":" + (default.length > 1 ? default[1] : defaultDate));
}
I have a string like this:
"core/pages/viewemployee.jsff"
From this code, I need to get "viewemployee". How do I get this using Java?
Suppose that you have that string saved in a variable named myString.
String myString = "core/pages/viewemployee.jsff";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("."));
But you need to make the same control before doing substring in this one, because if there aren't those characters you will get a "-1" from lastIndexOf(), or indexOf(), and it will break your substring invocation.
I suggest looking for the Javadoc documentation.
You can solve this with regex (given you only need a group of word characters between the last "/" and "."):
String str="core/pages/viewemployee.jsff";
str=str.replaceFirst(".*/(\\w+).*","$1");
System.out.println(str); //prints viewemployee
You can split the string first with "/" so that you can have each folder and the file name got separated. For this example, you will have "core", "pages" and "viewemployee.jsff". I assume you need the file name without the extension, so just apply same split action with "." seperator to the last token. You will have filename without extension.
String myStr = "core/pages/viewemployee.bak.jsff";
String[] tokens = myStr.split("/");
String[] fileNameTokens = tokens[tokens.length - 1].split("\\.");
String fileNameStr = "";
for(int i = 0; i < fileNameTokens.length - 1; i++) {
fileNameStr += fileNameTokens[i] + ".";
}
fileNameStr = fileNameStr.substring(0, fileNameStr.length() - 1);
System.out.print(fileNameStr) //--> "viewemployee.bak"
These are file paths. Consider using File.getName(), especially if you already have the File object:
File file = new File("core/pages/viewemployee.jsff");
String name = file.getName(); // --> "viewemployee.jsff"
And to remove the extension:
String res = name.split("\\.[^\\.]*$")[0]; // --> "viewemployee"
With this we can handle strings like "../viewemployee.2.jsff".
The regex matches the last dot, zero or more non-dots, and the end of the string. Then String.split() treats these as a delimiter, and ignores them. The array will always have one element, unless the original string is ..
The below will get you viewemployee.jsff:
int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
String fileNameWithExtn = idx >= 0 ? fileName.substring(idx + 1) : fileName;
To remove the file Extension and get only viewemployee, similarly:
idx = fileNameWithExtn.lastIndexOf(".");
String filename = idx >= 0 ? fileNameWithExtn.substring(0,idx) : fileNameWithExtn;
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]", "");
Is there a simple solution to parse a String by using regex in Java?
I have to adapt a HTML page. Therefore I have to parse several strings, e.g.:
href="/browse/PJBUGS-911"
=>
href="PJBUGS-911.html"
The pattern of the strings is only different corresponding to the ID (e.g. 911). My first idea looks like this:
String input = "";
String output = input.replaceAll("href=\"/browse/PJBUGS\\-[0-9]*\"", "href=\"PJBUGS-???.html\"");
I want to replace everything except the ID. How can I do this?
Would be nice if someone can help me :)
You can capture substrings that were matched by your pattern, using parentheses. And then you can use the captured things in the replacement with $n where n is the number of the set of parentheses (counting opening parentheses from left to right). For your example:
String output = input.replaceAll("href=\"/browse/PJBUGS-([0-9]*)\"", "href=\"PJBUGS-$1.html\"");
Or if you want:
String output = input.replaceAll("href=\"/browse/(PJBUGS-[0-9]*)\"", "href=\"$1.html\"");
This does not use regexp. But maybe it still solves your problem.
output = "href=\"" + input.substring(input.lastIndexOf("/")) + ".html\"";
This is how I would do it:
public static void main(String[] args)
{
String text = "href=\"/browse/PJBUGS-911\" blahblah href=\"/browse/PJBUGS-111\" " +
"blahblah href=\"/browse/PJBUGS-34234\"";
Pattern ptrn = Pattern.compile("href=\"/browse/(PJBUGS-[0-9]+?)\"");
Matcher mtchr = ptrn.matcher(text);
while(mtchr.find())
{
String match = mtchr.group(0);
String insMatch = mtchr.group(1);
String repl = match.replaceFirst(match, "href=\"" + insMatch + ".html\"");
System.out.println("orig = <" + match + "> repl = <" + repl + ">");
}
}
This just shows the regex and replacements, not the final formatted text, which you can get by using Matcher.replaceAll:
String allRepl = mtchr.replaceAll("href=\"$1.html\"");
If just interested in replacing all, you don't need the loop -- I used it just for debugging/showing how regex does business.
I have a URL and I want it to look like this:
Action Manatee - Action
http://xxxxxx.com/songs2/Music%20Promotion/Stream/Action%20Manatee%20-%20Action.mp3
What is the syntax for trimming up to where it after this "Stream/" and make spaces where the %20 is. I also want to trim the .mp3
Hmm, for that particular example, I would split the string according to the '/' character then trim the text that follows the final '.' character. Finally, do a replace of "%20" into " ". That should leave you with the string you want
Tested
String initial = "http://xxxxxx.com/songs2/Music%20Promotion/Stream/Action%20Manatee%20-%20Action.mp3";
String[] split = initial.split("/");
String output = split[split.length-1];
int length = output.lastIndexOf('.');
output = output.substring(0, length);
output = output.replace("%20", " ");
String urlParts[] = URL.split("\/");
String urlLast = urlParts[length-1];
String nameDotMp = urlLast.replaceAll("%20");
String name = nameDotMp.substring(0,nameDotMp.length-5);
You could use the split() and replace() methods to accomplish this, here are two ways:
Split your string apart by using the forward slashes:
string yourUrl = [URL Listed];
//Breaks your URL into sections on slashes
string[] sections = yourUrl.split("\/");
//Grabs the last section after the slashes, and replaces the %20 with spaces
string newString = sections[sectiongs.length-1].replace("%20"," ");
Split your string at the Stream/ section: (Only use this if you can guarantee it will be in that form)
string yourUrl = [URL Listed];
//This will get everything after Stream (your song name)
string newString = yourUrl.split("Stream\/")[1];
//Replaces your %20s with spaces
newString = newString.replace("%20"," ");
URL songURL = new URL("yourpath/filename");
String filename = songURL.getFile();