This question already has answers here:
How to extract numbers from a string and get an array of ints?
(13 answers)
Closed 4 years ago.
I have a string like this 3x^2 I want to extract the first and the second number and store them in an array. and if they didn't exist they should be considered as 1.
EDIT :
For example in string x the first and the second number are 1
or in string 3x the second number is 1. I think it should be clear now.
Just get digits with the Regex:
String str = "3x^2";
String pattern = "(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
ArrayList<Integer> numbers = new ArrayList<>();
Find with Matcher all numbers and add them to the ArrayList. Don't forget to convert them to int, because m.group() returns the String.
while (m.find()) {
numbers.add(Integer.parseInt(m.group()));
}
And if your formula doesn't contain the second number, add there your desired default item.
if (numbers.size<2) {
numbers.add(1);
}
Finally print it out with:
for (int i: numbers) {
System.out.print(i + " ");
}
And the output for 3x^2 is 3 2.
And for the 8x it is 8 1.
if the numbers are allways separated by x^, just split the string using this separator
String[] splitted = "3x^2".split("x\\^");
Related
This question already has answers here:
Converting String to Number in Java
(9 answers)
Closed 1 year ago.
Hi everyone I am trying to get the numeric value inside a string. So far this method works well for me to obtain integers. But now I would also like to be able to obtain numbers that contain decimals.
if I want to extract the number that a String contains I use:
getNumbers("delay: 5 days")
output = 5
Now I want to get the number of "this a sample, delay: 7.1 days"
output = 7.1
Remark: the str always can change, but always will have a number (integer or float)
public String getNumbers(String str){
str = str.replaceAll("[^\\d]", " ");
str = str.trim();
str = str.replaceAll(" +", " ");
if (str.equals(""))
return "-1";
return str;
}
You can use regex for retrieving only digits from string, try this:
String numbers = Double.valueOf(yourStrValue.replaceAll("[^\\d.]+|\\.(?!\\d)", "")).toString()
but watch out for discrete numbers will be merged by this way. For example if u have 34fdf^.98 this process produced 34.98
Try using Double.parseDouble(str) in order to parse the double value. However, keep in mind that you will need to remove all the non-number characters from the string.
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
Scanner sc = new Scanner(System.in);
String s = sc.nextLine().trim();
s= s.replaceAll("\\++"," + ");
Pattern p = Pattern.compile("[a-zA-Z]+|\\d+|[\\(\\*\\)/%]");
Matcher m = p.matcher(s);
while(m.find()){
String str=m.group();
s= s.replace(m.group()," "+str+" ").trim();
}
String[] str=s.split(" +");
for(String s1:str) System.out.print(s1+",");
if s=22*(7-9 output is: 22,*,(,7,-,9,
if s=12*(4-2 output is:1,2,*,(,4,-,2,
Why digits of 12 got separated in second example?
Help me if someone knows about it
It happens because there are two 2 in the last expression. When you get the last 2, you add spaces around all 2s, so it leads to 12 to be split.
This question already has answers here:
Java Regex group 0
(2 answers)
Closed 4 years ago.
I am trying to write a regex for a string which has a format [digit] [to] [digit] eg. 1 to 5 in which if I find a word "to" from a given string i want to extract the number before and after, I have tried this and it's not working.
Pattern p = Pattern.compile("([0-9]+)\\bto\\b([0-9]+)");
Matcher m = p.matcher("1 to 5");
m.find();
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));
Expected o/p
1
to
5
Consider adding a group for the to part.
Also for the space, you want \\s not \\b:
Pattern p = Pattern.compile("([0-9]+)\\s(to)\\s([0-9]+)");
Matcher m = p.matcher("1 to 5");
m.find();
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
And as said in the comments :
" Group zero denotes the entire pattern"
Is it necessary that you must use regex. If not, you can use String functions.
String s="23 to 34";
String toString="to";
if(s.contains(toString)){
int startIndex=s.indexOf(toString);
int endIndex=startIndex+(toString).length();
String s1=s.substring(0, startIndex); //get the first number
String s2=s.substring(endIndex); //get the second number
System.out.println(s1.trim()); // Removing any whitespaces
System.out.println(toString);
System.out.println(s2.trim();
}
This question already has answers here:
How to get substrings from strings [duplicate]
(4 answers)
Closed 4 years ago.
I am new to Java. I want to ask how to search for a general sub-string within a given string.
For example:-
In the string 12345.67 I want to search for the sub-string .67
And in the string 1.00 I want to search for the string .00.
I basically want to search for the string after the radical (.), provided the number of characters after radical are only 2.
According to my knowledge search for general sub-string is not possible, I thereby asked for your help.
I wish to print the input (stored in the database) , a floating point number, into Indian Currency format, i.e, comma separated.
I even looked at various previous posts but none of them seemed to help me as almost everyone of them failed to produce the requite output for decimal point
According to my knowledge search for general sub-string is not possible
So you may learn a bit more, here String substring(int beginIndex) method :
String str = "12345.67";
String res = str.substring(str.indexOf('.')); // .67
If you want to check that there is only 2 digits after . :
String str = "12345.67";
String res = str.substring(str.indexOf('.') + 1); // 67
if(res.length() == 2)
System.out.println("Good, 2 digits");
else
System.out.println("Holy sh** there isn't 2 digits);
You can use split plus the substring to achieve your objective
String test = "12345.67";
System.out.println(test.split("\\.")[1].substring(0,2));
In the split function, you can pass the regex with which you could give the separator and in a substring function with the number of characters you want to extract
Next to the answer provided from #azro you may also use regex:
String string = "12345.67";
Pattern ppattern = Pattern.compile("\\d+(\\.\\d{2})");
Matcher matcher = pattern.matcher(string);
if(matcher.matches()){
String sub = matcher.group(1);
System.out.println(sub);
}
Which prints:
.67
String str = "12345.67";
String searchString = "." + str.split("\\.")[1];
if(str.contains(searchString)){
System.out.println("The String contains the subString");
}
else{
System.out.println("The String doesn't contains the subString");
}
This question already has answers here:
what is the Java equivalent of sscanf for parsing values from a string using a known pattern?
(8 answers)
Closed 5 years ago.
I have a string and I want to a) check if it matches the following format and b) extract the numbers and text into variables:
"x:x:x - some text" // x = some integer number
In, C, I would use :
sscanf(str1, "%d:%d:%d - %s\n", &x, &y,&z, str2);
How do I do the same in Java?
Did you mean :
String text = "1:99:33 - some text";
boolean check = text.matches("\\d+:\\d+:\\d+ - .*");
System.out.println(check);
If you want to match exact (one number):(two numbers):(two number) you can use \\d:\\d{2}:\\d{2} instead of \\d+:\\d+:\\d+
details
\\d+ match one or more digit
: literal character
\\d+ match one or more digit
: literal character
\\d+ match one or more digit
- one space hyphen one space
.* zero or more any character
...how do I extract the numbers and the text from the string?
If you are using Java 8 you can split your input, the first input return numbers separated by :, the second is the text you want, so to extract the numbers, you need to split the first input again by : then Iterate over them and convert each one to an Integer, like this :
String input = "1:99:33 - some text";
String[] split = input.split(" - ");//Split using space hyphen space
String text = split[1];//this will return "some text"
List<Integer> numbers = Arrays.asList(split[0].split(":")).stream()
.map(stringNumber -> Integer.parseInt(stringNumber))
.collect(Collectors.toList());// this will return list of number [1, 99, 33]
The alternatve solution:
String input = "1:99:33 - some text";
StringTokenizer st = new StringTokenizer(input, ":");
while (st.hasMoreTokens()) {
String token = st.nextToken();
System.out.println(token);
}
StringTokenizer break the string into tokens. Where ":" is a tokens delimiter.
Output:
1
99
33 - some text