Extract date from a string [duplicate] - java

This question already has answers here:
Regex date format validation on Java
(12 answers)
Closed 8 years ago.
I would like to find date from java string.But i can not able to do this please help
String : 01-02-2014 <2>
Ineed output like :01-02-2014
My code:
public String rejex(String idate){
String result = null;
try{
String regex = "([1-9]|[012][0-9]|3[01])[-/]\\s*(0[1-9]|1[012])[-/]\\s*((19|20)?[0-9]{2})";
result = idate.replaceAll(regex, "$1-$2-$3");
}catch(Exception e){}
return result;
}

You are replacing what you are after (the date segments) with themselves.
If you want to extract it, this will work:
String regex = "(([1-9]|[012][0-9]|3[01])[-/]\\s*(0[1-9]|1[012])[-/]\\s*((19|20)?[0-9]{2})).*?<(\\d+)>";
String str = "This is a random string 01-02-2014 <123> this is another part of that random string";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println("Date: " + m.group(1));
System.out.println("Number: " + m.group(6));
}
Yields:
Date: 01-02-2014
Number: 123

just extract \\d\\d-\\d\\d-\\d{4} out, let SimpleDateFormat do the parsing job.

if space is there all the time then it's simple.
String dateStr = "01-02-2014 <2>"
String dateSplit[] = dateStr.split(" ");
//dateSplit[0] is what u are looking for
or
String dateStr = "01-02-2014 <2>"
String dateSplit[] = dateStr.split("<");
//dateSplit[0].trim() is what u are looking for
and then simply use SimpleDateFormat to converting it into Date.

Related

Split the get the value using java [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 4 years ago.
I have a reply message in a String and I want to split it to extract a value.
My String reply message format is:
REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE,...);
My requirement is to get the value ABC024049364194 from the above string format.
I tried using this code, but it hasn't worked:
String[] arrOfStr = str.split(",", 5);
for (String a : arrOfStr)
System.out.println(a);
If you split the String, you will simply need to access the token at index 2.
// <TYPE>(<ARGUMENTS>)
String message = "REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE);";
Matcher m = Pattern.compile("(\\w+)\\((.+)\\)").matcher(message);
if (m.find()) {
String type = m.group(1);
String[] arguments = m.group(2).split(",");
System.out.println(type + " = " + arguments[2]); // REPLY = ABC024049364194
}
public static void main(String[] args) {
String str = "REPLY(MSGID,15,ABC024049364194,SERVICE,10,CREATE,...)";
String code = str.split(",")[2];
System.out.println(code);
}
Will work if your code is always after 2 coma

Get Date Pattern from the random string

I have a scenario to return "YYYYMMDD" from "v={YYYYMMDD}" with out using String literal methods like split, substring etc.
Is there anyway I can use the dateUtil methods or any regex?
Thanks.
Using regex -
String input = "v={YYYYMMDD}";
String regex = "^v=\\{([^}]{8})\\}$";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.find()) {
System.out.println("Date pattern - " + m.group(1));
} else {
System.out.println("No date found!");
}
Result -
Date pattern - YYYYMMDD

Java - How to deal with ${param} [duplicate]

This question already has answers here:
Java generating Strings with placeholders
(12 answers)
Closed 4 years ago.
The client passed me a parameter str = "${param0},${param1}".
I want to replace ${param0} ${param1} with the value I queried from the database.
such as
//str = "${param0},${param1}"
//str = "${param0},${param1}, ${param2}"
//...
public String format(String str) {
String param0 = repository.query0();
//expect
str = "param0,${param1}";
String param1 = repository.query1();
//expect
str = "param0,param1,${param2}";
return str;
}
I know that java.lang.String#replace can solve the problem. But the parameter str is indefinite. It could also be str = "${param0}, ${param1}, ${param2}" or more. Is there any way to satisfy my request?
If you can be confident that it will always be in the format of ${paramX} then you can do the following:
String str = ...;
for (int i = 0; i < results.length; i++)
{
str = str.replace("${param" + i + "}", results[i]);
}
Replace the contents of the for loop and the resutls[i] portion to be however you access the data returned from your query.
If you instead can't dependent on ${paramX} being in sequential order, you can use a more hacky solution by using the following code:
// create a new StringBuilder to reduce concatentation
StringBuilder result = new StringBuilder();
// our warped string input
String str = "${param0}, ${param12}${param1234}${param2}";
// split it anywhere that is formatted with ${paramXXXX}
String[] parts = str.split("\\$\\{param[0-9]{1,}\\}");
// loop through the pieces
for (int i = 0; i < parts.length; i++)
{
// get the parts of the string that are not ${paramXXXX}
result.append(parts[i]);
// the results from the query.
result.append(queryResults[i]); // Replace with the proper way to read your query results
}
The above code should work no matter the input, as long as there are the same number of query results as there are ${paramXXXX} pieces in the input string.
Be sure to replace the code followed by // Replace with ... with the code to read your query results.
Here is an approach using matcher:
String str = "${param0},${param1}, ${param2}";
System.out.println("Matching: "+str);
Pattern regex = Pattern.compile("\\$\\{(\\w+)\\}");
Matcher matcher = regex.matcher(str);
while (matcher.find()){
System.out.println("found: "+matcher.group());
str = matcher.replaceFirst("results");
matcher = regex.matcher(str);
}
System.out.println("Result: "+str);
This is not very efficient, but easy to use. If you have gigabyte-scale computations, consider looping over your input string and compare characters manually.
Update:
Here is a better approach. More efficient and not susceptible for endless loop if results contain the pattern.
String str = "[${param0},${param1}, ${param2}]";
System.out.println("Matching: " + str);
final Pattern regex = Pattern.compile("\\$\\{(\\w+)\\}");
final Matcher matcher = regex.matcher(str);
final StringBuilder sb = new StringBuilder(str.length());
int prevMatch = 0;
while (matcher.find()) {
System.out.println("found: " + matcher.group());
sb.append(str.substring(prevMatch, matcher.start()));
sb.append("results");
prevMatch = matcher.end();
}
sb.append(str.substring(prevMatch, str.length()));
System.out.println("Result: " + sb.toString());

How to extract a string between two delimiters [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
substring between two delimiters
I have a string like
"ABC[ This is to extract ]"
I want to extract the part "This is to extract" in java. I am trying to use split, but it is not working the way I want. Does anyone have suggestion?
If you have just a pair of brackets ( [] ) in your string, you can use indexOf():
String str = "ABC[ This is the text to be extracted ]";
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
If there is only 1 occurrence, the answer of ivanovic is the best way I guess. But if there are many occurrences, you should use regexp:
\[(.*?)\] this is your pattern. And in each group(1) will get you your string.
Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
m.group(1); //is your string. do what you want
}
Try as
String s = "ABC[ This is to extract ]";
Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
Matcher m = p.matcher(s);
m.find();
String text = m.group(1);
System.out.println(text);
String s = "ABC[This is to extract]";
System.out.println(s);
int startIndex = s.indexOf('[');
System.out.println("indexOf([) = " + startIndex);
int endIndex = s.indexOf(']');
System.out.println("indexOf(]) = " + endIndex);
System.out.println(s.substring(startIndex + 1, endIndex));

Split a string to extract double value out of it

How can I convert String s="3.78 hi bye" to double c=3.78?
Same question for String s="hi 3.78 hi bye" (take only 3.78 while ignoring the text before)
You can use a regex to get rid of all characters that are not a digit or a .:
String s = "hi 3.78 hi bye";
String numberOnly = s.replaceAll("[^0-9\\.]+", "");
double d = Double.parseDouble(numberOnly); //d == 3.78d
You should add some exception handling in case the original string is not properly formatted.
you may try to use regular expression
Pattern doubleValue = Pattern.compile("\\d+\\.\\d+");
Matcher m = doubleValue.match(yourString);
if (m.find()) {
return Double.parseDouble(m.group(0));
}
return null;

Categories