In my program I need to loop through a variety of dates. I am writing this program in java, and have a bit of experience with readers, but I do not know which reader would complete this task the best, or if another class would work better.
The dates would be input into a text file in the format as follows:
1/1/2013 to 1/7/2013
1/8/2013 to 1/15/2013
Or something of this manner. I would need to break each range of dates into 6 local variables for the loop, then change them for the next loop. The variables would be coded for example:
private static String startingMonth = "1";
private static String startingDay = "1";
private static String startingYear = "2013";
private static String endingMonth = "1";
private static String endingDay = "7";
private static String endingYear = "2013";
I imagine this could be done creating several delimiters to look for, but I do not know that this would be the easiest way. I have been looking at this post for help, but cant seem to find a relevant answer. What would be the best way to go about this?
There are several options.
You could use the scanner, and set the delimiter to include the slash. If you want the values as ints and not string, just use sc.nextInt()
Scanner sc = new Scanner(input).useDelimiter("\\s*|/");
// You can skip the loop to just read a single line.
while(sc.hasNext()) {
startingMonth = sc.next();
startingDay = sc.next();
startingYear = sc.next();
// skip "to"
sc.next()
endingMonth = sc.next();
endingDay = sc.next();
endingYear = sc.next();
}
You can use regex, as alfasin suggest, but this case is rather simple so you can just match the first and last space.
String str = "1/1/2013 to 1/7/2013";
String startDate = str.substring(0,str.indexOf(" "));
String endDate = str.substring(str.lastIndexOf(" ")+1);ยจ
// The rest is the same:
String[] start = startDate.split("/");
System.out.println(start[0] + "-" + start[1] + "-" + start[2]);
String[] end = endDate.split("/");
System.out.println(end[0] + "-" + end[1] + "-" + end[2]);
String str = "1/1/2013 to 1/7/2013";
Pattern pattern = Pattern.compile("(\\d+/\\d+/\\d+)");
Matcher matcher = pattern.matcher(str);
matcher.find();
String startDate = matcher.group();
matcher.find();
String endDate = matcher.group();
String[] start = startDate.split("/");
System.out.println(start[0] + "-" + start[1] + "-" + start[2]);
String[] end = endDate.split("/");
System.out.println(end[0] + "-" + end[1] + "-" + end[2]);
...
OUTPUT
1-1-2013
1-7-2013
Related
I am trying to find and replace in the file using java but unable to get the solution.
File contents are
"ProductCode" = "8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}"
"ProductCode" = "8:.NETFramework,Version=v4.5"
I have to update the guid of first one which is 3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5
String line = "\"ProductCode\" = \"8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}\"";
String pattern = "[\"]([P][r][o][d][u][c][t][C][o][d][e]).+([\"])(\\s)[\"][8][:][{]";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
System.out.println(m.matches());
I am getting false.
please provide the solution if possible.
Thanks in advance.
"ProductCode" = "8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}" This is of the form:
quote + ProductCode + quote + whitespace + equals + whitespace +
quote + number + colon + any + quote
A simple Regex for this is \"ProductCode\"\s*=\s*\"\d:(.+)\"
When we escape this to a Java string we get \\\"ProductCode\\\"\\s*=\\s*\\\"\\d:(.+)\\\"
Try this pattern:
String pattern = "^\\\"(ProductCode)\\\"\\s\\=\\s\\\"\\w\\:\\{(\\w+\\-*\\w+\\-\\w+\\-\\w+\\-\\w+)\\}\\\"$";
Using regex for this problem is like taking a sledgehammer to break a nut. Rather simple:
final String line = "\"ProductCode\" = \"8:{3E3CDCB6-286C-4B7F-BCA6-D347A4AE37F5}\"";
final String prefix = "\"ProductCode\" = \"8:{";
final int prefixIndex = line.indexOf(prefix);
final String suffix = "}\"";
final int suffixIndex = line.indexOf(suffix);
final String guid = line.substring(prefixIndex + prefix.length(), suffixIndex);
I want to convert a date to words. For example: 12/12/2012 --> twelve twelve two thousand twelve and I already made number to word converter. But now I have problem to print it out.
Here my code:
String patternString = "\\d{2}/\\d{2}/\\d{4}"; // date regex
Pattern pattern = Pattern.compile(patternString); // pattern compiling
Matcher matcher = pattern.matcher(nom); // matching with pattern with input text from user
if (matcher.find()) {
String get_data = matcher.group();
if(get_data.contains("/")){ // check either has "/" slash or not
String parts[] = get_data.split("[/]"); // split process
String get_day = parts[0]; // day will store in first array
String get_month = parts[1]; // month will store in second array
String get_year = parts[2]; // year will store in third array
String s = NumberConvert.convert(Integer.parseInt(get_day))
+ NumberConvert.convert(Integer.parseInt(get_month))
+ NumberConvert.convert(Integer.parseInt(get_year));
String replace = matcher.replaceAll(s); // replace number to words
System.out.println(replace);
}
} else {...}
Input text from user:
12/12/2012 +++ 23/11/2010
But the result print only first pattern and next pattern also replace with value of first pattern too.
twelve twelve two thousand twelve +++ twelve twelve two thousand twelve
Please suggest me the solution
An immediate solution to your problem would be to use Matcher.replaceFirst(), instead of Matcher.replaceAll(), since you only want the first date pattern to be replaced with your written version of the date.
String replace = matcher.replaceFirst(s);
If you would like to be able to process each numeric date one at a time, you can do so in a left-to-right fashion using this code:
String patternString = "\\d{2}/\\d{2}/\\d{4}";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(nom);
String output = "";
while (matcher.find()) {
String get_data = matcher.group();
String parts[] = get_data.split("/");
String get_day = parts[0];
String get_month = parts[1];
String get_year = parts[2];
String s = NumberConvert.convert(Integer.parseInt(get_day)) +
NumberConvert.convert(Integer.parseInt(get_month)) +
NumberConvert.convert(Integer.parseInt(get_year));
if (output.equals("")) {
output = s;
}
else {
output += " +++ " + s;
}
String replace = matcher.replaceFirst("");
matcher = pattern.matcher(replace);
}
After each iteration, the above code resets the Matcher using a string from which the previous date matched has been removed. This lets you "eat" one date at a time, from left to right, building the human readable date output as you go along.
I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.
I have tried the following but I am geting the error in the title.
Simple:
[06:15, 06:45, 07:16, 07:46]
Result should look as this:
06:15 06:45 07:16 07:46
Code:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll(" ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");
But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:
StringBuilder builder = new StringBuilder();
for (String timeEntry: entry.getValue()) {
builder.append(timeEntry);
}
String after = builder.toString();
How to detect the letters in a String and switch them?
I thought about something like this...but is this possible?
//For example:
String main = hello/bye;
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
}else{
//nothing
}
Well, if you are interested in a cheeky regex :P
public static void main(String[] args) {
String s = "hello/bye";
//if(s.contains("/")){ No need to check this
System.out.println(s.replaceAll("(.*?)/(.*)", "$2/$1")); // () is a capturing group. it captures everything inside the braces. $1 and $2 are the captured values. You capture values and then swap them. :P
//}
}
O/P :
bye/hello --> This is what you want right?
Use String.substring:
main = main.substring(main.indexOf("/") + 1)
+ "/"
+ main.substring(0, main.indexOf("/")) ;
You can use String.split e.g.
String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.
String newString = splitUp[1] + "/" + splitUp[0];
Of course you have to also implement some error handling when there is no slash etc..
you can use string.split(separator,limit)
limit : Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array
String main ="hello/bye";
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
String[] parts = main.split("/",1);
main = parts[1] +"/" + parts[0] ; //main become 'bye/hello'
}else{
//nothing
}
Also you can use StringTokenizer to split the string.
String main = "hello/bye";
StringTokenizer st = new StringTokenizer(main,"\");
String part1 = st.nextToken();
String part2 = st.nextToken();
String newMain = part2 + "\" + part1;
I am trying to find a regular expression that would match the following format:
path/*.file_extension
For example:
temp/*.jpg
usr/*.pdf
var/lib/myLib.so
tmp/
Using the regex, I want to store the matching parts into a String array, such as:
String[] tokens;
// regex magic here
String path = tokens[0];
String filename = tokens[1];
String extension = tokens[2];
In case of the last case tmp/, that contains no filename and extension, then token[1] and token[2] would be null.
In case of the:
usr/*.pdf
then the token[1] would contain only the string "*".
Thank you very much for your help.
If you can use Java7 then you can use named groups like this
String data = "temp/*.jpg, usr/*.pdf, var/lib/*.so, tmp/*, usr/*, usr/*.*";
Pattern p = Pattern
.compile("(?<path>(\\w+/)+)((?<name>\\w+|[*]))?([.](?<extension>\\w+|[*]))?");
Matcher m = p.matcher(data);
while (m.find()) {
System.out.println("data=" + m.group());
System.out.println("path=" + m.group("path"));
System.out.println("name=" + m.group("name"));
System.out.println("extension=" + m.group("extension"));
System.out.println("------------");
}
This code should wotk:
String line = "var/lib/myLib.so";
Pattern p = Pattern.compile("(.+?(?=/[^/]*$))/([^.]+)\\.(.+)$");
Matcher m = p.matcher(line);
List<String> tokens = new ArrayList<String>();
if (m.find()) {
for (int i=1; i <= m.groupCount(); i++) {
tokens.add(m.group(i));
}
}
System.out.println("Tokens => " + tokens);
OUTPUT:
Tokens => [var/lib, myLib, so]
I'm assuming you're using Java. This should work:
Pattern.compile("path/(.*?)(?:\\.(file_extension))?");
Why use a regular expression?
I personally find lastIndexOf more readable.
String path;
String filename;
#Nullable String extension;
// Look for the last slash
int lastSlash = fullPath.lastIndexOf('/');
// Look for the last dot after the last slash
int lastDot = fullPath.lastIndexOf('.', lastSlash + 1);
if (lastDot < 0) {
filename = fullPath.substring(lastSlash + 1);
// If there is no dot, then there is no extension which
// is distinct from the empty extension in "foo/bar."
extension = null;
} else {
filename = fullPath.substring(lastSlash + 1, lastDot);
extension = fullPath.substring(lastDot + 1);
}
On a different approach, a simple usage of 'substring()/lastIndexOf()' methods should serve the purpose:
String filePath = "var/lib/myLib.so";
String fileName = filePath.substring(filePath.lastIndexOf('/')+1);
String path = filePath.substring(0, filePath.lastIndexOf('/'));
String fileName = fileName.substring(0, fileName.lastIndexOf('.'));
String extension = fileName.substring(fileName.lastIndexOf('.')+1);
Please Note: You need to handle the alternate scenarios e.g. file path without extension.