I'm trying to create a Java program that is able to follow the order of operations when infix expressions are entered. To simplify input I've decided it would be best to split the entire String by using a regex expression. I've been able to split everything except the 6 3 into their own String values in the splitLine array. My SSCCE attempt at this is as follows:
String line = "6 + 5 + 6 3 + 18";
String regex = "(?<=[-+*/()])|(?=[-+*/()])"; //Not spitting 6 3 correctly
String[] splitLine = line.split(regex);
for (int i=0; i<splitLine.length; i++) {
System.out.println(splitLine[i]);
}
Output:
6
+
5
+
6 3 //Error here
+
18
Expected Output:
6
+
5
+
6 //Notice
3 //these
+
18
I've tried and tried to modify my regex expression and have been unsuccessful. Could anyone tell me why my regex expression isn't splitting the 6 and the 3 into their own Strings in the splitLine array?
Edit: Just wanted to point out that I am doing this for fun, it is not for any sort of school work, etc. I just wanted to see if I could write a program to perform simple infix expressions. I do agree that there are better ways to do this and if the expression were to become more complicated I would run into some issue. But unfortunately this is how my book recommended I approach this step.
Thanks again for all of the quick comments and answers!
try this : (?<=[-+*/()])|(?=[-+*/()]|\\s{2,})
you can try adding a space in the regex, this will also split when there is 2 or more space as in this case 6 and 3 is separated by space, 6 3 will also be separated. this regex will spit the string if more than 2 space is matched. You can change the minimum number of space as \s{min,} in the regex
Following regex would match your current input.
\s(\w+|[-+*/()])
The gist is to search for a whitespace followed by a word or specific character from your list.
Output
6
+
5
+
6
3
+
18
You can use something like that maybe?
String line = "6 + 5 + 6 3 + 18";
String regex = "(?<=[-+*/() ])|(?=[-+*/() ])"; //Added space to character class
String[] splitLine = line.split(regex);
for (int i=0; i<splitLine.length; i++) {
if (splitLine[i].trim().equals("")) // Check for blank elements
continue;
System.out.println(splitLine[i].trim());
}
Or you can split your string on (?<=\\d)\\s+(?=\\d) to get 6 + 5 + 6 and 3 + 18.
Related
Example:
I/p : "its 2 3 4 5 n and ita 3 5"
O/p : 2345
So it should remove all white spaces from the digit
i tried couple of regex expression inside string.replace() but none of them worked .please help me
I think this might help
String numbers = str.replaceAll("\\D","");
You can try it like this.
String yourValue = "its 2 3 4 5 n and ita 3 5";
yourValue = yourValue .replaceAll("[^0-9]", "");
System.out.println(a);
Edit: I just realized, that your questeion is a bit confusing also. In my example the output would be "234535", which is different from what you wrote in your question. But I think there is no generalizable solution for this, that you want to cut off everything starting from the n if you really do want this.
If you want to pull all numerical values from a String then you can do something like this:
String string = "its 2 3 4 5 n and 32.45 it's a 3 5".replace(" ","");
Pattern p = Pattern.compile("-?\\d{1,3}(,?\\d{2,3})*?\\.?\\d+|-?\\d+(\\.\\d+)?");
List<String> list = new ArrayList<>();
Matcher m = p.matcher(str);
while (m.find()) {
list.add(m.group());
}
// Display the list contents.
System.out.println(list);
As you can see, this code can capture signed or unsigned Integer or floating point values from a string.
For the Regular Expression explaination, see the Tools section within this link.
This question already has answers here:
How to split a string with any whitespace chars as delimiters
(13 answers)
Closed 5 years ago.
I'm looking for a way to convert a string to an array and strip all whitespaces in the process. Here's what I have:
String[] splitArray = input.split(" ").trim();
But I can't figure out how to get rid of spaces in between the elements.
For example,
input = " 1 2 3 4 5 "
I want splitArray to be:
[1,2,3,4,5]
First off, this input.split(" ").trim(); won't compile since you can't call trim() on an array, but fortunately you don't need to. Your problem is that your regex, " " is treating each space as a split target, and with an input String like so:
String input = " 1 2 3 4 5 ";
You end up creating an array filled with several empty "" String items.
So this code:
String input = " 1 2 3 4 5 ";
// String[] splitArray = input.split("\\s+").trim();
String[] splitArray = input.trim().split(" ");
System.out.println(Arrays.toString(splitArray));
will result in this output:
[1, , , , , , , , 2, 3, 4, , , , , , 5]
What you need to do is to create a regex that greedily groups all the spaces or whitespace characters together, and fortunately we have this ability -- the + operator
Simply use a greedy split with the whitespace regex group
String[] splitArray = input.trim().split("\\s+");
\\s denotes any white-space character, and the trailing + will greedily aggregate one or more contiguous white-space characters together.
And actually, in your situation where the whitespace is nothing but multiples of spaces: " ", this is adequate:
String[] splitArray = input.trim().split(" +");
Appropriate tutorials for this:
short-hand character classes -- discusses \\s
repetition -- discusses the + also ? and * repetition characters
Try:
String[] result = input.split(" ");
*Edit 2,"undeclared variable" The following is the example that my textbook provides. I may have used incorrect terms in saying undeclared variable.
String fName = "Harry";
String lName = "Morgan";
String name = fName + lName;
results in the string "HarryMorgan"
What if you’d like the first and last name separated by a space? No problem:
String name = fName + " " + lName;
This statement concatenates three strings:
fName, the string literal " ", and lName.
The result is"Harry Morgan"
The citation provided is a guideline. Please check each citation for accuracy before use.
*Edit, Question is: How do I insert characters into an undeclared string?
Example:
Input: X839WS21R4E877
Display: X-839 WS21 R4-E87 (7)
Input: x83rws21b3e87a
Display: X-83R WS21 B3-E87 (A)
I am taking a 14 character input from the user. I need to format in spaces and " - " into the input. Also all of the letters need to be capitalized, although I have that already taken care of.
The following code is what I have.
System.out.println("Please enter your 14 character code.");
String name = input.nextLine();
if (name.length()>14) {//code thanks to namlik from stackoverflow
String cutName = name.substring(0, 14).toUpperCase();
name = cutName;
}
System.out.print(name);
Here is another post I found I feel might work but I don't understand how to implement it into my code or if it would work. Basic way to insert character into string.
The following link is to another similar question. Python vs of Question
This link is what came up when I tried to do a search however I am not using int to string so I don't believe it is relevant. Example of search results
I believe my scenario would benefit others to be able to insert other types of characters into an unknown string. I realize that using / you can insert special characters. However everything I have found so far uses the assumption that you are using a declared variable.
I believe I need to insert the characters I desire spaces and " - " at set points using the .substring(x, x) method however I am unsure how to go about doing so with out messing up my limit of only 14 characters.
Thank you in advance for your help.
If i understand your input output example correctly then the best way is to use regex groups and String::replaceAll like this :
String[] strings = {"X839WS21R4E877", "x83rws21b3e87a"};
for(String str : strings){
str = str.toUpperCase();// to convert the string to UpperCase
str = str.replaceAll("([A-Z0-9])([A-Z0-9]{3})([A-Z0-9]{4})([A-Z0-9]{2})([A-Z0-9]{3})([A-Z0-9])",
"$1-$2 $3 $4-$5 ($6)");
System.out.println(str);
}
Outputs
X-839 WS21 R4-E87 (7)
X-83R WS21 B3-E87 (A)
regex demo
details
([A-Z0-9])([A-Z0-9]{3})([A-Z0-9]{4})([A-Z0-9]{2})([A-Z0-9]{3})([A-Z0-9])
You have to devide your inputs to groups in the previouse regew there are 6 groups :
([A-Z0-9]) groupe 1 matches first letter or numbers
([A-Z0-9]{3}) groupe 3 matches 3 letters or numbers
([A-Z0-9]{4}) groupe 4 matches 4 letters or numbers
([A-Z0-9]{2}) groupe 2 matches 2 letters or numbers
([A-Z0-9]{3}) groupe 3 matches 3 letters or numbers
([A-Z0-9]) groupe 6 matches last character
This question already has answers here:
java - after splitting a string, what is the first element in the array?
(4 answers)
Closed 7 years ago.
I wrote the following Java code for testing the split() method in the String API.
import java.util.Scanner;
public class TestSplit {
public static void main(String[] args) {
String str = "10 5";
String[] integers = str.split(" ");
int numOfInt = integers.length;
for (int i = 0; i < numOfInt; i++) {
System.out.println(integers[i]);
}
}
}
I noticed that the above code gives me an output of
10
5
which is to be expected.
However, if I change the contents of str to " 10 5" then I get
10
5
as output. I don't understand why the output is different from the one above. If I am splitting str by using " " as a delimiter, then I thought that all " " will be ignored. So what is the extra space doing in my output?
EDIT: I tried " 10 5" and got
10
5
as output.
If you have a delimiter as the first character, split will return an empty String as the first element of the output array (i.e. " 10 5".split(" ") returns the array {"","10","5"}).
Similarly, if you have two consecutive delimiters, split will produce an empty String. So "10 5".split(" ") will produce the array {"10","","5"}.
If you wish leading and trailing whitespace to be ignored, change str.split(" "); to str.trim().split(" ");.
I thought a problem for a day but still cannot solve it.
I have a formula input like "11+1+1+2". without space
I want to split the formula according to the operator.
Then I wrote like these:
String s = "11+1+1+2";
String splitByOp[] = s.split("[+|-|*|/|%]");
for(int c=0; c < splitByOp.length; c++){
System.out.println(splitByOp[c]);
The output is:
11
1
1
2
I want to put the operand(the output) and also the operator(+) into an ArrayList. But how can I keep the operator after spliting them?
I try to have one more Array to split the number.
String operator[] = s.split("\\d");
But the result is 11 become 1 1. The length of operator[] is 5.
In other words, how can I perform like:
The output:
11
+
1
+
1
+
2
You need to split on a regex that is non consuming. Specifically, on "word boundary":
String[] terms = s.split("\\b");
A "word boundary" is the gap between the word char and a non-word char, but digits are classified as word chars. Importantly, the match is non-consuming, so all of the content of the input is preserved in the split terms.
Here's some test code:
String s = "11+1+1+2";
String[] terms = s.split("\\b");
for (String term : terms)
System.out.println(term);
Output:
11
+
1
+
1
+
2
public static void main(String[] args) {
String s = "11+1+1+2";
String[] terms = s.split("(?=[+])|(?<=[+])");
System.out.println(Arrays.toString(terms));
}
output
[11, +, 1, +, 1, +, 2]
You could combine lookahead/lookbehind assertions
String[] array = s.split("(?=[+])|(?<=[+])");