I have read whole xml file as single string using class.The output is
String result=<?xml version="1.0"?><catalog><book id="bk101"><part1><date>Fri Apr 05 11:46:46 IST 2013</date><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price> <publish_date>2000-10-01</publish_date></part1></book></catalog>
Now i want to replace date value.so first i want to extract date from the string and replace new value.I have following code,
Date date=new Date()
String str=result.substring(result.indexOf("<date>"));
It displays whole string from date tag to end tag.
How to extract date tag and replace it?
This here gets the contents of the tags using regex... but as for replacing it - I'll get back to you.
String result = "<?xml version=\"1.0\"?><catalog><book id=\"bk101\"><part1><date>Fri Apr 05 11:46:46 IST 2013</date><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price> <publish_date>2000-10-01</publish_date></part1></book></catalog>";
String pattern = ".*(?i)(<date.*?>)(.+?)(</date>).*";
System.out.println(result.replaceAll(pattern, "$2"));
Cheers
String str=result.substring(result.indexOf("<date>") ,result.indexOf("</date>")+"</date>".length());
String#substring(int beginIndex)
Returns a new string that is a substring of this string. The substring
begins with the character at the specified index and extends to the
end of this string.
String#substring(int beginIndex,int endIndex)
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at
index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
Edit: Oh, you wanted it in java. This is the C# solution =)
You can solve this by replacing the entire date including the tag.
You have two dates in your XML so to be sure that you will not replace both of them you can do it like this.
int index1 = result.IndexOf("<date>");
int index2 = result.IndexOf("</date>") - index1 + "</date>".Length;
var stringToReplace = result.Substring(index1, index2);
var newResult = result.Replace(stringToReplace, "<date>" + "The Date that you want to insert" + "</date>");
Just the value:
String str = result.substring(result.indexOf("<date>") + "<date>".length(),
result.indexOf("</date>"));
Including the tags:
String str = result.substring(result.indexOf("<date>"),
result.indexOf("</date>") + "</date>".length());
Related
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
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 am getting a piece of JSON text from a url connection and saving it to a string currently as such:
...//setting up url and connection
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str = in.readLine();
When I print str, I correctly find the data {"build":{"version_component":"1.0.111"}}
Now I want to extract the 111 from str, but I am having some trouble.
I tried
String afterLastDot = inputLine.substring(inputLine.lastIndexOf(".") + 1);
but I end up with 111"}}
I need a solution that is generic so that if I have String str = {"build":{"version_component":"1.0.111111111"}}; the solution still works and extracts 111111111 (ie, I don't want to hard code extract the last three digits after the decimal point)
If you cannot use a JSON parser then you can this regex based extraction:
String lastNum = str.replaceAll("^.*\\.(\\d+).*", "$1");
RegEx Demo
^.* is greedy match that matches everything until last DOT and 1 or more digits that we put in group #1 to be used in replacement.
Find the start and the end indexes of the String you need and substring(start, end) :
// String str = "{"build":{"version_component":"1.0.111"}};" cannot compile without escaping
String str = "{\"build\":{\"version_component\":\"1.0.111\"}}";
int start = str.lastIndexOf(".")+1;
int end = str.lastIndexOf("\"");
String substring = str.substring(start,end);
just use JSON api
JSONObject obj = new JSONObject(str);
String versionComponent= obj.getJSONObject("build").getString("version_component");
Then just split and take the last element
versionComponent.split("\\.")[2];
Please, your can try the following code :
...
int index = inputLine.lastIndexOf(".")+1 ;
String afterLastDot = inputLine.substring(index, index+3);
With Regular Expressions (Rexp),
You can solve your problem like this ;
Pattern pattern = Pattern.compile("111") ;
Matcher matcher = pattern.matcher(str) ;
while(matcher.find()){
System.out.println(matcher.start()+" "+matcher.end());
System.out.println(str.substring(matcher.start(), matcher.end()));
}
The following is a sample line from a CSV file I'm trying to parse using regex or string.split(","), and I want to extract the year (in below example, 2013). But the problem is: the year column index is not always 17, it could also be 19. I am thinking of looping through the each string in the string.split(",") array and match the pattern against "2XXX".
9344949,HW488429,10/09/2013 05:00:00 AM,039XX W MONROE
ST,0610,BURGLARY,FORCIBLE
ENTRY,RESIDENCE,false,false,1122,011,28,26,05,1149955,1899326,**2013**,10/16/2013
12:39:00 AM,41.87966141386545,-87.72485045045373,"(41.87966141386545,
-87.72485045045373)"
This can break down each line in the CSV file
Pattern.compile("^([^,]+,){2}\\d{2}/\\d{2}/(\\d{4})([^,]+,){3}([^,]+)");
But I need some help matching each string against 2XXX. Tried this:
Pattern patt = Pattern.compile("^2\d{3}"); however, my eclipse reports error on this.
Firstly, I strongly advise you try using a CSV parser like Boris suggested.
IF you must do it your way you could do something like
String year;
String str = // your csv line
String[] strArr = str.split(",");
for(String s : strArr)
{
if(s.trim().matches("2\\d{3}"))
{
year = s;
break;
}
}
I have a String which contains a date, for example "01-01-2012", then an space and then the time "01:01:01". The complete string is: "01-01-2012 01:01:01"
I would like to extract only the date from this string so at the end I would have "01-01-2012" but don't know how to do this.
Four options (last two added to make this one answer include the options given by others):
Parse the whole thing as a date/time and then just take the date part (Joda Time or SimpleDateFormat)
Find the first space using indexOf and get the leading substring using substring:
int spaceIndex = text.indexOf(" ");
if (spaceIndex != -1)
{
text = text.substring(0, spaceIndex);
}
Trust that it's valid in the specified format, and that the first space will always be at index 10:
text = text.substring(0, 10);
Split the string by spaces and then take the first result (seems needlessly inefficient to me, but it'll work...)
text = text.split(" ")[0];
You should consider what you want to happen if there isn't a space, too. Does that mean the data was invalid to start with? Should you just continue with the whole string? It will depend on your situation.
Personally I would probably go with the first option - do you really want to parse "01-01-2012 wibble-wobble bad data" as if it were a valid date/time?
String input = "01-01-2012 01:01:01";
String date = d.split(" ")[0];
Try this:
String date = s.substring(0, s.indexOf(" "));
Or even (because the length is fixed):
String date = s.substring(0, 10);
Or use StringUtils.substringBefore():
String date = StringUtils.substringBefore(s, " ");
Lots of ways to do this, a very simple method is to split the String at the space and use the first part (which will be the date):
String dateTime = "01-01-2012 01:01:01";
String date = dateTime.split(" ")[0];
You can use String.split() and take only the relevant String in your resultng String[] [in your example, it will be myString.split(" ")[0]
In that case where only one space is in the string, you can use String.split(" "). But this is a bad practice. You should parse the date with a DateFormat
.
You can use substring to extract the date only:
String thedatetime = "01-01-2012 01:01:01";
String thedateonly = thedate.substring(0, 10);
You should really read through the javadoc for String so you are aware of the available functions.
If you know in advance this is the format of the string, I'd do this:
public String getDateOnly(String fullDate){
String[] spl = fullDate.split(" ");
return spl[0];
}
You can do it either using string manipulation API:
String datetime = "01-01-2012 01:01:01";
int spacePos = datetime.indexOf(" ");
if (spacePos > 0) {
String date = datetime.substring(0, spacePos - 1);
}
or using regular expression:
Pattern p = Pattern.compile("(\\d{2}-\\d{2}-\\d{4})");
String datetime = "01-01-2012 01:01:01";
Matcher m = p.matcher(datetime);
if(m.find()) {
String date = m.group(1);
}
or using SimpleDateFormat
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = fmt.parse(datetime);
Calendar c = Calendar.getInstance();
c.setTime(date);
String date = c.getDayOfMonth() + "-" + c.getMonth() + "-" + c.getYear();
Use String.substring(int, int). If you are interested in the value of the date and time, then use SimpleDateFormatter to parse your string.
myString.substring(0,10);
If your string is always in that format (2 digits, minus, 2 digits, minus, 4 digits, space etc...) then you can use substring(int beginIndex, int endIndex) method of string to get what you want.
Note that second parameter is the index of character after returning substring.
If you want to explode the complete date from the string use this method.
/**
* #param dateTime format string
* #param type type of return value : "date" or "time"
* #return String value
*/
private String getFullDate(String dateTime, String type) {
String[] array = dateTime.split(" ");
if (type == "time") {
System.out.println("getDate: TIME: " + array[1]);
return array[1];
} else if (type == "date") {
System.out.println("getDate: DATE: " + array[0]);
return array[0];
} else {
System.out.println("NULL.");
return null;
}
}
Otherwise if you want only the date for explample 01-01-2012
use this:
/**
* #param datetime format string
* #return
*/
private String getOnlyDate(String datetime) {
String array[] = datetime.split("-");
System.out.println("getDate: DATE: " + array[0]);
return array[0];
}
I hope my answer will help you.