how can I possible split this string using "-" but also store the negative sign for "-5". I'm using
string = "5*5--5";
String[] sub = string.split("-");
Output :
[5*5, , 5]
Output that I want:
[5*5, -5]
Related
public static void main(String[] args) {
String title = "Today, and tomorrow,2,1,2,5,0";
String[] titleSep = title.split(",");
System.out.println(Arrays.toString(titleSep));
System.out.println(titleSep[0]);
System.out.println(titleSep[1]);
}
output:
[Today, and tomorrow, 2, 1, 2, 5, 0]
Today
(space) and tomorrow
I want to treat "Today, and tomorrow" as a phrase representing the first index value of titleSep (do not want to separate at comma it contains).
What is the split method argument that would split the string only at commas NOT followed by a space?
(Java 8)
Use a negative look ahead:
String[] titleSep = title.split(",(?! )");
The regex (?! ) means "the input following the current position is not a space".
FYI a negative look ahead has the form (?!<some regex>) and a positive look ahead has the form (?=<some regex>)
The argument to the split function is a regex, so we can use a negative lookahead to split by comma-not-followed-by-space:
String title = "Today, and tomorrow,2,1,2,5,0";
String[] titleSep = title.split(",(?! )"); // comma not followed by space
System.out.println(Arrays.toString(titleSep));
System.out.println(titleSep[0]);
System.out.println(titleSep[1]);
The output is:
[Today, and tomorrow, 2, 1, 2, 5, 0]
Today, and tomorrow
2
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
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("(?=[+])|(?<=[+])");
I am trying to parse the certain name from the filename.
The examples of File names are
xs_1234323_00_32
sf_12345233_99_12
fs_01923122_12_12
I used String parsedname= child.getName().substring(4.9) to get the 1234323 out of the first line. Instead, how do I format it for the above 3 to output only the middle numbers(between the two _)? Something using split?
one line solution
String n = str.replaceAll("\\D+(\\d+).+", "$1");
most efficent solution
int i = str.indexOf('_');
int j = str.indexOf('_', i + 1);
String n = str.substring(i + 1, j);
String [] tokens = filename.split("_");
/* xs_1234323_00_32 would be
[0]=>xs [1]=> 1234323 [2]=> 00 [3] => 32
*/
String middleNumber = tokens[2];
You can try using split using the '_' delimiter.
The String.split methods splits this string around matches of the given ;parameter. So use like this
String[] output = input.split("_");
here output[1] will be your desired result
ANd input will be like
String input = "xs_1234323_00_32"
I would do this:
filename.split("_", 3)[1]
The second argument of split indicates the maximum number of pieces the string should be split into, in your case you only need 3. This will be faster than using the single-argument version of split, which will continue splitting on the delimiter unnecessarily.
I've got a string '123' (yes, it's a string in my program). Could anyone explain, when I use this method:
String[] str1Array = str2.split(" ");
Why I got str1Array[0]='123' rather than str1Array[0]=1?
str2 does not contain any spaces, therefore split copies the entire contents of str2 to the first index of str1Array.
You would have to do:
String str2 = "1 2 3";
String[] str1Array = str2.split(" ");
Alternatively, to find every character in str2 you could do:
for (char ch : str2.toCharArray()){
System.out.println(ch);
}
You could also assign it to the array in the loop.
str2.split("") ;
Try this:to split each character in a string .
Output:
[, 1, 2, 3]
but it will return an empty first value.
str2.split("(?!^)");
Output :
[1, 2, 3]
the regular expression that you pass to the split() should have a match in the string so that it will split the string in places where there is a match found in the string. Here you are passing " " which is not found in '123' hence there is no split happening.
Because there's no space in your String.
If you want single chars, try char[] characters = str2.toCharArray()
Simple...You are trying to split string by space and in your string "123", there is no space
This is because the split() method literally splits the string based on the characters given as a parameter.
We remove the splitting characters and form a new String every time we find the splitting characters.
String[] strs = "123".split(" ");
The String "123" does not have the character " " (space) and therefore cannot be split apart. So returned is just a single item in the array - { "123" }.
To do the "Split" you must use a delimiter, in this case insert a "," between each number
public static void main(String[] args) {
String[] list = "123456".replaceAll("(\\d)", ",$1").substring(1)
.split(",");
for (String string : list) {
System.out.println(string);
}
}
Try this:
String str = "123";
String res = str.split("");
will return the following result:
1,2,3