String format Java - java

I would like to do the following thing:
I have a String in Java, for instance
"4231354"
My aim is to show a version number in this way
XXX-X-X.XX
which means than I need to use a function to show
"423-1-3.54"
Thanks.

You can try this too:
StringBuilder str = new StringBuilder("4235167");
str.insert(3, '-');
str.insert(5, '-');
str.insert(7, '.');
System.out.println(str);

You can do it with replaceAll, like this:
String ver = "4231354";
String fmt = ver.replaceAll("(\\d{3})(\\d)(\\d)(\\d{2})", "$1-$2-$3.$4");
Regular expression defined by the first parameter has four groups - a group of three characters, two groups of single characters, and a group of two characters. The second parameter uses these groups, which are numbered $1 through $4, to produce the formatting that you are looking to achieve.
Demo.

I like the old way
As you mentioned length is fixed so you can use substring
String st="4231354";
String newString=st.substring(0,3)+"-"+st.substring(3,4)+"-"+st.substring(4,5)+"."+st.substring(5,st.length());
System.out.println(newString);
DEMO

If you want to get
"423-1-3.54"
All you have to do is:
String originalNumber = "4231354";
String versionNumber = new String(originalNumber.substring(0, 3) + "-" + originalNumber.substring(3, 4) + "-" + originalNumber.substring(4, 5) + "." + originalNumber.substring(5));

Or use String.format()
public Format(String version) {
String v = String.format("%s-%s-%s.%s",
version.substring(0,3),
version.substring(3,4),
version.substring(4,5),
version.substring(5,7));
System.out.println(v);
}

Related

How to remove unknown characters from a string which follows a particular format?

I have a String in this format: &?0907141|somename|5009-07-2014|sample
All I want to do is to remove 50 from the above String format, but the number might be anything not just 50, I cannot go by index position since the text "somename" might be changed to something else, but String will always be in the same format as above.
How do I remove it in the easiest possible way?
This will remove two characters after the second pipe.
String s = "&?0907141|somename|5009-07-2014|sample";
System.out.println(s.replaceFirst("(.*\\|.*\\|)..(.*\\|.*)", "$1$2"));
try this
String.replaceAll ("\\|[0-9]{2}", "|");
it will replace a pipe and 2 digits with a pipe
1. String[] arr= `String#split()` on `|`
2. use replace() / regex etc on arr[2].
3. Code..
String s = "&?0907141|somename|5009-07-2014|sample";
String splits[] = s.split("\\|");
s = splits[0] + "|" + splits[1] + "|" + splits[2].substring(2) + "|" + splits[3];

Java string split with Multiple Characters Delimiter

I have a very complicated output from a function, which i need to use specific word from it.
For example, my output is:
oracle 11257 1 0 14:01 ? 00:00:00 ora_pmon_sas
I need to get just "sas" word, which is next to "ora_pmon_"
Another example:
oracle 6187 1 0 13:41 ? 00:00:00 ora_pmon_db2
I need to get "db2". So what should be my expression?
JAVA code:
insArray=line.split("what will be between these quotes?");
You could just do
String sub = s.substring(s.indexOf("ora_pmon_") + 9);
How about this one?
string = string.replaceAll(".*?ora_pmon_", "");
If you want multiple words in place of ora, then it will be
string = string.replaceAll(".*?(ora|kf|asm)_pmon_", "");
You can simply use String#substring(int i) combined with String#lastIndexOf(char ch)
For example:
String result = input.substring(input.lastIndexOf('_') + 1)

How to split this string in java?

I have this code
lStock.setText(" Put " + getLoc(i));
At the moment it prints out like this on the GUI:
3I031C
what I want to show now on the screen GUI is:
3I03-1C
I tried testing the split() but I'm confused.
String.split is used to break apart a string based on some particular delimiter. You don't have a delimiter here.
If you always want to break after the fourth character:
String str = "3I031C";
String out = str.substring(0, 4) + '-' + str.substring(4);
You can't use the split method since it needs a delimiter, but you're string doesn't contain any.
You can try using substring:
str = str.substring(0, 4) + "-" + str.substring(4);
But this will only work if the string always have the same length and format.
If its a fixed output try like below
s = s.substring(0, 4) + "-" + s.substring(4);
refer to String.substring()

Need to match a string with following regex format

A String will be of format [( 1.0N)-195( 1.0E)-195(28)-769.7(NESW)-1080.8(U)-617.9(43-047-30127)]
I need a regex to match to see if the string contains -XXX-XXX (where X is a digit)
Pattern p = Pattern.compile("(?=.*?(?:-[0-9][0-9][0-9]-[0-9][0-9][0-9]))");
if(p.matcher(a).matches())
{
System.out.println("Matched");
}
Also I've tried -[0-9][0-9][0-9]-[0-9][0-9][0-9] and (?=.*?-[0-9][0-9][0-9]-[0-9][0-9][0-9])
Nothing worked
A substring would be much easier, but (?:\\d{2})(-\\d{3}-\\d{5}) will match -XXX-XXXXX as the 1 group.
I'm assuming the 3 digits in the last number was a mistake. If not just change the 5 to a 3.
If you want to check if the string contains -3digits-3digits
String a = "43-037-30149";
Pattern p = Pattern.compile(".*(-[0-9]{3}-[0-9]{3})");
if(p.matcher(a).matches())
{
System.out.println("Matched");
}
why don't you use substring??
String b = a.substring(2,9);
or this one:
String c = a.substring(a.indexOf('-'), a.indexOf('-') + 8);
making "only" a substring would also be much more efficient! ;)

Use String.split() with multiple delimiters

I need to split a string base on delimiter - and .. Below are my desired output.
AA.BB-CC-DD.zip ->
AA
BB
CC
DD
zip
but my following code does not work.
private void getId(String pdfName){
String[]tokens = pdfName.split("-\\.");
}
I think you need to include the regex OR operator:
String[]tokens = pdfName.split("-|\\.");
What you have will match:
[DASH followed by DOT together] -.
not
[DASH or DOT any of them] - or .
Try this regex "[-.]+". The + after treats consecutive delimiter chars as one. Remove plus if you do not want this.
You can use the regex "\W".This matches any non-word character.The required line would be:
String[] tokens=pdfName.split("\\W");
The string you give split is the string form of a regular expression, so:
private void getId(String pdfName){
String[]tokens = pdfName.split("[\\-.]");
}
That means to split on any character in the [] (we have to escape - with a backslash because it's special inside []; and of course we have to escape the backslash because this is a string). (Conversely, . is normally special but isn't special inside [].)
Using Guava you could do this:
Iterable<String> tokens = Splitter.on(CharMatcher.anyOf("-.")).split(pdfName);
For two char sequence as delimeters "AND" and "OR" this should be worked. Don't forget to trim while using.
String text ="ISTANBUL AND NEW YORK AND PARIS OR TOKYO AND MOSCOW";
String[] cities = text.split("AND|OR");
Result : cities = {"ISTANBUL ", " NEW YORK ", " PARIS ", " TOKYO ", " MOSCOW"}
pdfName.split("[.-]+");
[.-] -> any one of the . or - can be used as delimiter
+ sign signifies that if the aforementioned delimiters occur consecutively we should treat it as one.
I'd use Apache Commons:
import org.apache.commons.lang3.StringUtils;
private void getId(String pdfName){
String[] tokens = StringUtils.split(pdfName, "-.");
}
It'll split on any of the specified separators, as opposed to StringUtils.splitByWholeSeparator(str, separator) which uses the complete string as a separator
String[] token=s.split("[.-]");
It's better to use something like this:
s.split("[\\s\\-\\.\\'\\?\\,\\_\\#]+");
Have added a few other characters as sample. This is the safest way to use, because the way . and ' is treated.
Try this code:
var string = 'AA.BB-CC-DD.zip';
array = string.split(/[,.]/);
You may also specified regular expression as argument in split() method ..see below example....
private void getId(String pdfName){
String[]tokens = pdfName.split("-|\\.");
}
s.trim().split("[\\W]+")
should work.
you can try this way as split accepts varargs so we can pass multiple parameters as delimeters
String[]tokens = pdfName.split("-",".");
you can pass as many parameters that you want.
If you know the sting will always be in the same format, first split the string based on . and store the string at the first index in a variable. Then split the string in the second index based on - and store indexes 0, 1 and 2. Finally, split index 2 of the previous array based on . and you should have obtained all of the relevant fields.
Refer to the following snippet:
String[] tmp = pdfName.split(".");
String val1 = tmp[0];
tmp = tmp[1].split("-");
String val2 = tmp[0];
...

Categories