Actually I'm trying to replace number to words in the sentence that giving by user. This case date format; For example: My birthday is on 16/6/2000 and I'm newbie to the java --> become ---> My birthday is on sixteenth july two thousand and I'm newbie to the java
Here is code:
Scanner reader = new Scanner(System.in);
System.out.println("Enter any numbers: ");
String nom = reader.nextLine(); // get input from user
//checking contains that has "/" or not
if(nom.contains("/")){
String parts[] = nom.split("[/]");
String part1 = parts[0]; //data before "/" will be stored in the first array
String day[] = part1.split("\\s+");// split between space
String get_day = day[day.length -1];// get last array
String get_month = parts[1]; //data in the between of "/" will be stored in the second array
String part3 = parts[2]; // data after "/" will be stored in the third array
String year[] = part3.split("\\s+");// split between space
String get_year = year[0];// get first array
String s = NumberConvert.convert(Integer.parseInt(get_day)) +
NumberConvert.convert(Integer.parseInt(get_month)) +
NumberConvert.convert(Integer.parseInt(get_year));
String con = nom.replaceAll("[0-9].*/[0-9].*/[0-].*", s); // replace number to word
System.out.println(con); // print the data already converted
} else {....}
But the result that I have got is:
My birthday is on sixteenth july two thousand
//"and I'm newbie to the java" is disappear [How to solve it]//
How to solve it. Actually I want to get value before and after of "/" slash and convert it to words and replace it as a original input from user.
What I have tried is:
String con = nom.replaceAll("[0-9].*/[0-9].*/[0-9999]", s); // a bit change [0-9].* to [0-9999]
But output become like this:
My birthday is on sixteenth july two thousand 000 and I'm newbie to the java
//after two thousand index "000" is appearing
The regex is wrong:
[0-9].*/[0-9].*/[0-].*
What it means:
[0-9] match a single number in the range between 0 and 9
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
/ matches the character / literally
[0-9] match a single number in the range between 0 and 9
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
/ matches the character / literally
[0-] match a single number in the list 0- literally
.* matches any character (except newline) between zero and unlimited times, as many times as possible, giving back as needed [greedy]
It should be:
[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]
Or, better:
\d{2}/\d{2}/\d{4}
You can also use below regex pattern to get all the numbers from String:
String st = "My birthday is on 16/6/2000 and I'm newbie to the java, using since 2015";
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(st);
while (m.find()) {
System.out.println(m.group());
}
Related
This is the input: enter image description here
I want to get the last number but how? (1,2,6)
I tried this:
String line = scanner.nextLine();
String[] parts = line.split(" ");
int ProductCount =Integer.parseInt(parts[3].replaceAll(" ", ""));
If you want the last number you can do it like this.
.*? reluctantly grab the characters
(\\d+)$ - capture one or more digits at end of string.
$1 back reference to captured value (21 in this case)
and convert to an int.
String s = "kssk sk k22 s 21";
int v = Integer.parseInt(s.replaceAll(".*?(\\d+)$","$1"));
System.out.println(v);
prints
21
A somewhat better alternative might be to do the following if there is always a space before the last number.
get the last index of a white space
and starting with the next character, get the substring and convert to an integer.
int i = s.lastIndexOf(' '); // returns -1 if no space is found.
int v = Integer.parseInt(s.substring(i+1));
This question is similar to my previous question Split a string contain dash and minus sign. But I asked it in a wrong and then it got a slightly different semantics and people answered(including) in that perspective. Therefore rather than modifying that question I thought it's better to ask in a new question.
I have to split a string which contain hyphen-minus character and minus sign. I tried to split based on the unicode character (https://en.wikipedia.org/wiki/Hyphen#Unicode), still it considering minus sign same as hyphen-minus character. Is there a way I can solve it?
Expected output
(coun)
(US)
-1
Actual output
(coun)
(US)
// actually blank line will print here but SO editor squeezing the blank line
1
public static void main(String[] args) {
char dash = '-';
int i = -1;
String a = "(country)" + dash + "(US)" + dash + i;
Pattern p = Pattern.compile("-", Pattern.LITERAL);
String[] m = p.split(a);
for (String s : m) {
System.out.println(s);
}
}
char dash = '\u2010'; // 2010 is hyphen, 002D is hyphen-minus
int i = -1;
String a = "(country)" + dash + "(US)" + dash + i;
Pattern p = Pattern.compile("\u2010", Pattern.LITERAL);
String[] m = p.split(a);
for (String s : m) {
System.out.println(s);
}
The string representation of an integer always uses the hyphen-minus as the negative sign:
From Integer.toString:
If the first argument is negative, the first element of the result is the ASCII minus character '-' ('\u002D'). If the first argument is not negative, no sign character appears in the result.
so in the end your string has 3 hyphen-minus characters. That's why split can't distinguish between them.
Since you can't change the string representation of an integer, you need to change the dash variable to store a hyphen instead of hyphen-minus. Now there are 2 hyphens and 1 hyphen-minus in your string, making split able to distinguish between them.
I have a file which has line in the format
xbox one gaming-consoles:xbox-one-games:gaming-controllers
xbox one games xbox-one-games
xbox 360 games xbox-360-games:gaming-consoles
xbox 360 gaming-consoles:xbox-360-games:gaming-controllers
Now i want to split the lines in two parts . The logic of splitting is that it should be done at the first space before the character ':'
so the splited text should look like
xbox one gaming-consoles:xbox-one-games:gaming-controllers
xbox one games ox-one-games:gaming-controllers
xbox 360 games xbox-360-games:gaming-consoles
and so on....
How can this be acheived ?
You could use lastIndexOfto get the position within the string of the last space, then use substring to split the string into two different variables.
String s1 = "test string with lots of spaces";
String s2 = s1.substring(0, s1.lastIndexOf(" "); //From the first character until the last space
String s3 = s1.substring(s1.lastIndexOf(" ")+1); //Index of last space+1 to end.
System.out.println(s1 + "\n" + s2 + "\n" + s3);
Which gives the output of:
test string with lots of spaces
test string with lots of
spaces
A small problem would be that the string containing the first half would still contain the whitespace at the end of the string, but could be easily mediated if needed with trim.
Regarding
The logic of splitting is that it should be done at the first space before the character :
Use a positive lookahead based regex:
String s = "xbox one gaming-consoles:xbox-one-games:gaming-controllers and more here";
String[] chunks = s.split(" ++(?=[^ :]*:)", 2);
System.out.println(Arrays.toString(chunks));
// => [xbox one, gaming-consoles:xbox-one-games:gaming-controllers and more here]
See the Java demo
The split will yield one (if no match is found) or 2 chunks (since the limit argument is passed, 2). The split will happen at 1 or more spaces (see " ++") that are followed with 0+ chars other than a space and : (see [^ :]*) followed with a :.
Maybe you can use a regex to extract the second part of each line.
(\\s[\\S]+)(?=:).+ will lookahead (\\s[\\S]+) to check if it followed by a :. (\\s[\\S]+) select the group that begins with a space \s and followed by nonspace characters [\S]+.
Here is the sample code:
import java.util.regex.*;
public class TestRegex {
public static void main(String []args){
String[] line = new String[] {
"xbox one gaming-consoles:xbox-one-games:gaming-controllers",
"xbox one games xbox-one-games",
"xbox 360 games xbox-360-games:gaming-consoles",
"xbox 360 gaming-consoles:xbox-360-games:gaming-controllers "
};
String regex = "(\\s[\\S]+)(?=:).+";
Pattern re = Pattern.compile(regex);
for (String ln : line) {
Matcher m = re.matcher(ln);
if (m.find()) {
System.out.println(m.group(0));
}
}
}
}
If a string is a = 000102.45600. I need to convert it to a = ---102.45600.
Any help in java using either regex or String formatter?
Tried the following:
a = a.replaceFirst("^0+(?!$)","-");
but i am getting only a = -102.45600 not 3 dashes.
Rules: Any leading zeros before decimal in string should be replaced by that many dashes.
000023.45677 to ----23.45677
002345.56776 to --2345.56776
00000.45678 to -----.45678
Hopefully I am clear on what my need is?
String subjectString = "000102.45600";
String resultString = subjectString.replaceAll("\\G0", "-");
System.out.println(resultString); // prints ---102.45600
\G acts like \A (the start-of-string anchor) on the first iteration of replaceAll(), but on subsequent passes it anchors the match to the spot where the previous match ended. That prevents it from matching zeroes anywhere else in the string, like after the decimal point.
See: reference SO answer.
This should do it:
String number = //assign a value here
for (int i=number.length();i>0; i--) {
if (number.substring(0,i).matches("^0+$")) {
System.out.println(number.replaceAll("0","-"));
break;
}
}
This searches for the longest substring of number which starts at index 0 and consists entirely of zeroes - starting by checking the entire String, then shortening it until it finds the longest substring of leading zeroes. Once it finds this substring, it replaces each zero with a dash and breaks out of the loop.
Why not convert the start of the string to the "." to an integer, convert it back to a string then compare the lengths. 000102 length = 6. 102 length = 3. You would have your preceding zero count.
String s = "10.226.18.158:10.226.17.183:ABCD :AAAA"
My requirement is to split the string at up to 3rd : or up to 2nd :. i.e.
Something like String sa[] = s.split(), but with the regex splitting only up to 3rd or 2nd.
s[0] = "10.226.18.158"
s[1] = "10.226.17.183"
s[2] = "ABCD :AAAA"
According to the String#split() javadoc you can add a number to limit the number of splits.
s.split(":", 3);
Edit: as melwil metions This will return an array of up to the number passed in long.
So in your example of splitting up to 2nd : you would need to pass in 3.
s.split(":",3) returns the output
sa[0] = "10.226.18.158"
sa[1] = "10.226.17.183"
sa[2] = "ABCD :AAAA"
Relevent section quoted from the java doc about how the second argument (limit) works.
The limit parameter controls the number of times the pattern is
applied and therefore affects the length of the resulting array. If
the limit n is greater than zero then the pattern will be applied at
most n - 1 times, the array's length will be no greater than n, and
the array's last entry will contain all input beyond the last matched
delimiter. If n is non-positive then the pattern will be applied as
many times as possible and the array can have any length. If n is zero
then the pattern will be applied as many times as possible, the array
can have any length, and trailing empty strings will be discarded.
You can split your string basing on one non-whitespece character, \S{1}, followed by a colon, ::
String sa[] = s.split("\\S{1}:");