Java: get input string and change the format - java

I am getting an input string containing digits with comma (,) separated like these formats
1) X,X
2) X,XX
3) XX,X
My desired format is XX,XX.
I want if I get the input string like in above 1,2,3 formats it should be formatted as my desired format XX,XX.
For example,
1) If I get a string in this format 1,12. I want to put a zero before 1 like this 01,12.
2) If I get a string in this format 1,1. I want to put a zero before and ofter 1 like this 01,10.
3) If I get a string in this format 11,1. I want to put a zero after the last 1 like this 11,10.
Any help will be highly appreciated, thanks in advance.

You can use regex pattern to format in your specific pattern using Lookaround
(?=^\d,\d\d$)|(?<=^\d\d,\d$)|(?<=^\d,\d$)|(?=^\d,\d$)
Online demo
Here we are using three combination of data as given by you and empty space is replaced by zero.
Sample code:
String regexPattern="(?=^\\d,\\d\\d$)|(?<=^\\d\\d,\\d$)|(?<=^\\d,\\d$)|(?=^\\d,\\d$)";
System.out.println("1,12".replaceAll(regexPattern, "0"));
System.out.println("1,1".replaceAll(regexPattern, "0"));
System.out.println("11,1".replaceAll(regexPattern, "0"));
output:
01,12
01,10
11,10

Feed in your number to the function, and get the desired String result.
public static String convert(String s){
String arr[] = s.split(",");
if(arr[0].length()!=2){
arr[0] = "0"+arr[0];
}
if(arr[1].length()!=2){
arr[1] = arr[1]+"0";
}
return arr[0]+","+arr[1];
}
But it only works in the format described above.

If your goal is to print these strings, you could use the format method, and leading and trailing zeroes.
https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Object[] splitted = input.split(",");
System.out.println(String.format("%2s,%-2s", splitted).replace(' ','0'));

Related

Strip date from String with junk data - Java

I need to know if there is anyway to strip the date alone from text like below using java. I am trying to find something more generic, but couldn't get any help, As the input varies.
Some example inputs:
This time is Apr.19,2021 Cheers
or
19-04-2021 Cheers
or
This time is 19-APR-2021
I have seen some code which works for trailing junk characters but couldn't find anything if the date is in between the string and if it varies to different formats.
We could use String#replaceAll here for a regex one-liner approach:
String[] inputs = new String[] {
"This time is Apr.19,2021 Cheers",
"19-04-2021 Cheers",
"This time is 19-APR-2021",
"Hello 2021-19-Apr World"
};
for (String input : inputs) {
String date = input.replaceAll(".*(?<!\\S)(\\S*\\b\\d{4}\\b\\S*).*", "$1");
System.out.println(date);
}
This prints:
Apr.19,2021
19-04-2021
19-APR-2021
2021-19-Apr
If you assume a "date" is any series of letter/number/dot/comma/dash chars that ends with a 4-digit "word", match that and replace with a blank to delete it
str = str.replaceAll("\\b[A-Za-z0-9.,-]+\\b\\d{4}\\b", "");

Regex for epoch time in millisecond using java

I have this string:
String str = "8240d66c-4771-4fae-9631-8a420f9099ca,458,cross_vendor_certificate_will_expire,1565102543758";
I would like to remove the epoch time from the string using regex I've searched the web but I didn't find a suitable solution.
This is my code I have so far:
public void createHashMapWithAlertCSVContent() throws Exception {
for(String item: lstServer) { //lstServer is a list contains names of the CSV files
String[] contentCSVStr= CmdHelper.Remote.File.cat(SERVER,INDENI_INSIGHT_PATH + "/"+item).split("\n");//Function to get CSV contents
mapServer.put(FileUtil.removeExtension(item), contentCSVStr);//Finally I add each String[] to hashmap key is the csv file name and String[] is the content of each CSV file
}
Assert.assertEquals(mapServer.size(), lstServer.size());
mapServer.remove("job");
}
example of possible content:
1. 0,TRIAL,8240d66c-4771-4fae-9631-8a420f9099ca,1566345600000,5,1565102549213
2. 8240d66c-4771-4fae-9631-8a420f9099ca,0,1565102673040
3. 8240d66c-4771-4fae-9631-8a420f9099ca,0.0.0.develop,4418,1565102673009
EDIT:
regex might be any location in the string and might exit more than once in the string.
length of the epoch time string for sure > 10
String input = "0,TRIAL,8240d66c-4771-4fae-9631-8a420f9099ca,1566345600000,5,1565102549213";
String output = input.replaceAll("\\d{10,},|,\\d{10,}", "");
System.out.println(output);
Output:
0,TRIAL,8240d66c-4771-4fae-9631-8a420f9099ca,5
The vertical bar | in the regular expression denotes two options, one with a number and a comma, the other with the comma before the number. This takes into account that the timestamp may be first or last in the string or somewhere between.
\\d denotes a digit and {10,} that there are at least 10 of them with no upper limit. Please consider yourself whether the lower limit should be 10, 13 or some other number of digits.
Corner case: if the string consists of only one or more timestamps, the above replacement will not remove the last one of them since it insists on removing one comma with each timestamp, and a string consisting of only one timestamp will not have a comma in it.

Add character into middle of String

I need your help to turn a String like 12345678 into 1234.56.78
[FOUR DIGITS].[TWO DIGITS].[TWO DIGITS]
My code:
String s1 = "12345678";
s1 = s1.replaceAll("(\\d{4})(\\d+)", "$1.$2").replaceAll("(\\d{2})(\\d+)", "$1.$2");
System.out.println(s1);
But the result is 12.34.56.78
If you are sure that you'll always have the input in the same format then you can simply use a StringBuilder and do something like this:
String input = "12345678";
String output = new StringBuilder().append(input.substring(0, 4))
.append(".").append(input.substring(4, 6)).append(".")
.append(input.substring(6)).toString();
System.out.println(output);
This code creates a new String by appending the dots to the sub-strings at the specified locations.
Output:
1234.56.78
Use a single replaceAll() method with updated regex otherwise the second replaceAll() call will replace including the first four digits.
System.out.println(s1.replaceAll("(\\d{4})(\\d{2})(\\d+)", "$1.$2.$3")
This puts dots after every pair of chars, except the first pair:
str = str.replaceAll("(^....)|(..)", "$1$2.");
This works for any length string, including odd lengths.
For example
"1234567890123" --> "1234.56.78.90.12.3"

Java split with certain patern

String abc ="abc_123,low,101.111.111.111,100.254.132.156,abc,1";
String[] ab = abc.split("(\\d+),[a-z]");
System.out.println(ab[0]);
Expected Output:
abc_123
low
101.111.111.111,100.254.132.156
abc
1
The problem is i am not able to find appropriate regex for this pattern.
I would suggest to not solve all problems with one regular expression.
It seems that your initial string contains values that are separated by ",". So split those values with ",".
Then iterate the output of that process; and "join" those elements that are IP addresses (as it seems that this is what you are looking for).
And just for the sake of it: keep in mind that IP addresses are actually pretty complicated; a pattern "to match em all" can be found here
You could use lookahead and lookbehind to check, if 3 digits and a . at the correct place are preceding or following the ,:
String[] ab = abc.split("(?<!\\.\\d{3}),|,(?!\\d{3}\\.)");
String[] ab = abc.split(",");
System.out.println(ab[0]);
System.out.println(ab[1]);
int i = 2;
while(ab[i].matches("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}")) {
if(i > 2) System.out.print(",");
System.out.print(ab[i++]);
}
System.out.println();
System.out.println(ab[i++]);
System.out.println(ab[i++]);
first split them into array by , ,then apply regex to check whether it is in desired formate or not.If yes then concate all these separated by,
String abc ="abc_123,low,101.111.111.111,100.254.132.156,abc,1";//or something else.
String[] split = abc.split(",");
String concat="";
for(String data:split){
boolean matched=data.matches("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
if(matched){
concat=concat+","+data;
}else{
System.out.println(data);
}
}
if(concat.length()>0)
System.out.println(concat.substring(1));
}

Java - Extracting a string from another string

I have a String like this:
http://www.fam.com/FAM#Bruno12/06/2011
How can I cut http://www.fam.com/FAM# and 12/06/2011 in order to get only Bruno.
The format is always:
http://www.fam.com/FAM#NAMEDATE
Is there a simple way to do this? Can you just explain me how?
Simply do this:
myString = original.substring(23, original.length() - 10);
23 is for http://www.fam.com/FAM#
original.length() - 10 is for 12/06/2011
Use :
String str = "http://www.fam.com/FAM#Bruno12/06/2011";
String[] arr = str.split("#|[\\d+/]"); // last index of arr is Bruno
If the string always starts with http://www.fam.com/FAM# then it's simple: that's 23 characters, so take the substring from position 23 (note that indices are zero-based).
String input = "http://www.fam.com/FAM#Bruno12/06/2011";
String result = input.substring(23);
If you want everything after the first # in the string, then search for # and take everything that comes after it:
int index = input.indexOf('#');
String result = input.substring(index + 1);
(error checking omitted for simplicity).
To remove the date, remove the last 10 characters.
See the API documentation of class String for useful methods.
use regex #(.*?)\\d\\d/ to capture it.
You should use standard URL parsing code, as at Could you share a link to an URL parsing implementation?
I expect the URL parser can cope with the fact that your Ref (i.e. "Bruno12/06/2011") contains slashes.
URL url = new URL(inputString);
String nameDate = url.getRef();
expresses what you want to do in the simplest and clearest form.

Categories