Java Regex in round brackets - java

I am trying to parse an input string like this
String input = "((1,2,3),(3,4,5),(2,3,4),...)"
with the aim of getting an array of String where each element is an inner set of integers i.e.
array[0] = (1,2,3)
array[1] = (3,4,5)
etc.
To this end I am first of all getting the inner sequence with this regex:
String inner = input.replaceAll("\\((.*)\\)","$1");
and it works. Now I'd like to get the sets and I am trying this
String sets = inner.replaceAll("((\\((.*)\\),?)+","$1")
But I can't get the result I expected. What am I doing wrong?

Don't use replaceAll to remove the parentheses at the ends. Rather use String#substring(). And then to get the individual elements, again rather than using replaceAll, you should use String#split().
String input = "((1,2,3),(3,4,5),(2,3,4))";
input = input.substring(1, input.length() - 1);
// split on commas followed by "(" and preceded by ")"
String[] array = input.split("(?<=\\)),(?=\\()");
System.out.println(Arrays.toString(array));

Related

How to replace a specific character from a string given starting index

I am given a string = "SUBTOTAL(9,L7:L17)"
I want to replace all L with 2 in given string but L from SUBTOTAL should not be changed or replacing all L with 2 inside brackets.
I have tried with replaceAll() in java method but its replacing all L with 2
resulting "SUBTOTA2(9,27:217)" which is wrong
What i want like this
Result will be like : "SUBTOTAL(9,27:217)"
You can split your string into two substrings based on the first occurence of (, then replace your character on the second part and recombine the result:
String string = "SUBTOTAL(9,L7:L17)";
int replaceStartIndex = string.indexOf('(');
System.out.println(string.substring(0, replaceStartIndex)
+ string.substring(replaceStartIndex).replaceAll("L", "2"));
Outputs SUBTOTAL(9,27:217)

How to return only first n number of words in a sentence Java

Say i have a simple sentence as below.
For example, this is what have:
A simple sentence consists of only one clause. A compound sentence
consists of two or more independent clauses. A complex sentence has at
least one independent clause plus at least one dependent clause. A set
of words with no independent clause may be an incomplete sentence,
also called a sentence fragment.
I want only first 10 words in the sentence above.
I'm trying to produce the following string:
A simple sentence consists of only one clause. A compound
I tried this:
bigString.split(" " ,10).toString()
But it returns the same bigString wrapped with [] array.
Thanks in advance.
Assume bigString : String equals your text. First thing you want to do is split the string in single words.
String[] words = bigString.split(" ");
How many words do you like to extract?
int n = 10;
Put words together
String newString = "";
for (int i = 0; i < n; i++) { newString = newString + " " + words[i];}
System.out.println(newString);
Hope this is what you needed.
If you want to know more about regular expressions (i.e. to tell java where to split), see here: How to split a string in Java
If you use the split-Method with a limiter (yours is 10) it won't just give you the first 10 parts and stop but give you the first 9 parts and the 10th place of the array contains the rest of the input String. ToString concatenates all Strings from the array resulting in the whole input String. What you can do to achieve what you initially wanted is:
String[] myArray = bigString.split(" " ,11);
myArray[10] = ""; //setting the rest to an empty String
myArray.toString(); //This should give you now what you wanted but surrouned with array so just cut that off iterating the array instead of toString or something.
This will help you
String[] strings = Arrays.stream(bigstring.split(" "))
.limit(10)
.toArray(String[]::new);
Here is exactly what you want:
String[] result = new String[10];
// regex \s matches a whitespace character: [ \t\n\x0B\f\r]
String[] raw = bigString.split("\\s", 11);
// the last entry of raw array is the whole sentence, need to be trimmed.
System.arraycopy(raw, 0, result , 0, 10);
System.out.println(Arrays.toString(result));

Split String in java by specified pattern

How to split this String in java such that I'll get the text occurring between the braces in a String array?
GivenString = "(1,2,3,4,#) (a,s,3,4,5) (22,324,#$%) (123,3def,f34rf,4fe) (32)"
String [] array = GivenString.split("");
Output must be:
array[0] = "1,2,3,4,#"
array[1] = "a,s,3,4,5"
array[2] = "22,324,#$%"
array[3] = "123,3def,f34rf,4fe"
array[4] = "32"
You can try to use:
Matcher mtc = Pattern.compile("\\((.*?)\\)").matcher(yourString);
The best solution is the answer by Rahul Tripathi, but your question said "How to split", so if you must use split() (e.g. this is an assignment), then this regex will do:
^\s*\(|\)\s*\(|\)\s*$
It says:
Match the open-parenthesis at the beginning
Match close-parenthesis followed by open-parenthesis
Match the close-parenthesis at the end
All 3 allowing whitespace.
As a Java regex, that would mean:
str.split("^\\s*\\(|\\)\\s*\\(|\\)\\s*$")
See regex101 for demo.
The problem with using split() is that the leading open-parenthesis causes a split before the first value, resulting in an empty value at the beginning:
array[0] = ""
array[1] = "1,2,3,4,#"
array[2] = "a,s,3,4,5"
array[3] = "22,324,#$%"
array[4] = "123,3def,f34rf,4fe"
array[5] = "32"
That is why Rahul's answer is better, because it won't see such an empty value.
Usually, you would want to use the split() function as this is the easiest way to split a string into multiple arrays when the string is broken up by a key char.
The main problem is that you need information inbetween two chars. The easiest way to solve this problem would to go through the string get ride of every instance of '('. This leaves the string looking like
String = "1,2,3,4,#) a,s,3,4,5) 22,324,#$%) 123,3def,f34rf,4fe) 32)"
And this is perfect, as you can split by the char ')' and not worry about the other bracket interfering with the split. I suggest using the replace("","") where it replaces every instance of the first parameter with the second parameter (we can use "" to delete it).
Here is some example code that may work :
String a = "(1,2,3,4,#) (a,s,3,4,5) (22,324,#$%) (123,3def,f34rf,4fe) (32)"
a = a.replace("(","");
//a is now equal to 1,2,3,4,#) a,s,3,4,5) 22,324,#$%) 123,3def,f34rf,4fe) 32)
String[] parts = a.split("\\)");
System.out.println(parts[0]); //this will print 1,2,3,4,#
I haven't tested it completely, so you may end up with unwanted spaces at the end of the strings you may need to get rid of!
You can then loop through parts[] and it should have all of the required parts for you!

split string into array and add the delimiter to the array

i have an String and i need to split this String to array
My String is for example "-2x+3"
i split it with this code
public static String[] splitAnswer(String answerInput){
answerInput = answerInput.trim();
String[] token = answerInput.split("[\\+\\-\\*\\\\\\/]");
return token;
}
but i need the minus sign with 2x i.e. (-2x) and my array output will be {"-2x","3"}
the important thing i need the minus with the number after
You can use following regex:
String[] token = answerInput.split("[+*/]|(?=-)")
So, this splits on all the operators, except -. For - operator, it splits on empty string before the - operator. BTW, you don't need to escape anything inside the character class.
For -2x + 3, the split positions are:
|-2x+3 ( `|` is empty space)
^ ^

Using java code how to extract text from single quotes. Also a specific instance

I need to extract the third instance of text between single quotes using Java code.
Input text is: 'a','b','c'
Output text should be: c
Any help is appreciated.
you could do something simple and first split on the comma character from your string. myString.split(",")
This will supply you with an array containing ['a','b','c'] array[0] = 'a', array[1] = 'b'....
with then you can grab the third item or array[2] which will give you 'c'
You could then do a charAt(1) to retrieve this item. or if the item between the quotes is text, you could use substring to retrieve the item from the string.
So for array[2] = "'bleh'" you could use array[2].substring(1,array[2].length - 2); Just make sure to do validation as this could easily cause index out of range exceptions.
an example of this would be:
public String getThirdVal(String input)
{
String[] myArray = input.split(',');
String wantedValue = myArray[2].substring(1, myArray[2].length - 2);
return wantedValue;
}

Categories