How can I split a string by two delimiters? - java

I know that you can split your string using myString.split("something"). But I do not know how I can split a string by two delimiters.
Example:
mySring = "abc==abc++abc==bc++abc";
I need something like this:
myString.split("==|++")
What is its regularExpression?

Use this :
myString.split("(==)|(\\+\\+)")

How I would do it if I had to split using two substrings:
String mainString = "This is a dummy string with both_spaces_and_underscores!"
String delimiter1 = " ";
String delimiter2 = "_";
mainString = mainString.replaceAll(delimiter2, delimiter1);
String[] split_string = mainString.split(delimiter1);
Replace all instances of second delimiter with first and split with first.
Note: using replaceAll allows you to use regexp for delimiter2. So, you should actually replace all matches of delimiter2 with some string that matches delimiter1's regexp.

You can use this
mySring = "abc==abc++abc==bc++abc";
String[] splitString = myString.split("\\W+");
Regular expression \W+ ---> it will split the string based upon non-word character.

Try this
String str = "aa==bb++cc";
String[] split = str.split("={2}|\\+{2}");
System.out.println(Arrays.toString(split));
The answer is an array of
[aa, bb, cc]
The {2} matches two characters of the proceding character. That is either = or + (escaped)
The | matches either side
I am escaping the \ in java so the regex is actually ={2}|\+{2}

Related

Split or tokenise a java String using a substring as delimiter

How to split or tokenise a String in java not based on regex but based on a substring?
String str = "{A={111={i=[a,b,c],ii=[e,f]}, 222={iii=[a,e]}}, B={333={i= [b,c]}}};
Now I want to tokenise or split the string based on substring "}}," and not regex "}},".
Although the String.split(String regex) function specifies that it takes a regular expression as a parameter, that does not stop you from escaping any special characters and splitting on a literal string.
To escape special characters in a regular expression, you can make use of the Pattern.quote(String s) function, or you can escape the individual characters using backslashes \\:
String escapedStr = Pattern.quote("}},");
String alternativeEscapedStr = "\\}\\},";
For the example you have provided however, you shouldn't need to escape anything:
String str = "{A={111={i=[a,b,c],ii=[e,f]}, 222={iii=[a,e]}}, B={333={i= [b,c]}}}";
String[] splitStr = str.split(Pattern.quote("}},"));
System.out.println(Arrays.toString(splitStr));
String[] splitStr2 = str.split("}},");
System.out.println(Arrays.toString(splitStr2));
Output:
[{A={111={i=[a,b,c],ii=[e,f]}, 222={iii=[a,e], B={333={i= [b,c]}}}]
[{A={111={i=[a,b,c],ii=[e,f]}, 222={iii=[a,e], B={333={i= [b,c]}}}]
String str = "{A={111={i=[a,b,c],ii=[e,f]}, 222={iii=[a,e]}}, B={333={i= [b,c]}}}";
String[] split = str.trim().split("}},");
Arrays.stream(split).forEach(s-> System.out.println(s));

cant make this delimiter work, java split

I need help making a delimiter for multiple characters
I need a String delimiter for
these characters
( ) " ; : , ? ! .
I've tried:
private String delimiter = "()\":;,?!.";
private String delimiter = "[()\":;,?!.]";
private String delimiter = "\\(\\)\"\\:\\;\\,\\?\\!\\.";
Seems I can only make them work one at a time..
Any insight is greatly appreciated.
If it matters this is how its going into array:
foo = line.split(delim);
If you want to split on any of those characters, you can separate each one with an alternation: |. Otherwise, the string will only be split when all of those characters are present.
String delimiter = "\\(|\\)|\"|\\:|\\;|\\,|\\?|\\!|\\.";
Also, you're unnecessarily escaping a few characters, this would also work:
String delimiter = "\\(|\\)|\"|:|;|,|\\?|!|\\.";
Almost there with nr. 3
#Test
public void delim() {
String delimiter = "[\\(\\)\"\\:\\;\\,\\?\\!\\.]";
String[] split = "Hello(World)How:are;You;doing,today?You!sir.I mean"
.split(delimiter);
System.out.println(Arrays.toString(split));
}
Output
[Hello, World, How, are, You, doing, today, You, sir, I mean]
You missed the square brackets.
To avoid all the quoting you may use Pattern#quote
String delimiter = "[" + Pattern.quote("()\":;,?!.") + "]";
Returns a literal pattern String for the specified String.
This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.
Metacharacters or escape sequences in the input sequence will be given no special meaning.
| is required between:
delimiter = "\\(|\\)|\"|:|;|,|\\?|!|\\."

Java regex to split a string by using different delimiters

Suppose I want to split a string by either space character or the %20 string, how should I write my regex?
I tried the following, but it didn't work.
String regex = "[\\s+, %20]";
String str1 = "abc%20xyz";
String str2 = "abc xyz";
str1.split(regex);
str2.split(regex);
The regex doesn't seem to work on str1.
use the alternation |:
String regex = "(?:\\s+|%20)+";
String regex = "(\\s{1}+|%20{1}+)";
If you want to split by ONE space or ONE "%20", try this:
String regex = "(\\s|%20)";
If you want to split by AT LEAST ONE space or AT LEAST ONE "%20", then try this:
String regex = "(\\s+|(%20)+)";

Java - Split string

i have string which is separated by "." when i try to split it by the dot it is not getting spitted.
Here is the exact code i have. Please let me know what could cause this not to split the string.
public class TestStringSplit {
public static void main(String[] args) {
String testStr = "[Lcom.hexgen.ro.request.CreateRequisitionRO;";
String test[] = testStr.split(".");
for (String string : test) {
System.out.println("test : " + string);
}
System.out.println("Str Length : " + test.length);
}
}
I have to separate the above string and get only the last part. in the above case it is CreateRequisitionRO not CreateRequisitionRO; please help me to get this.
You can split this string through StringTokenizer and get each word between dot
StringTokenizer tokenizer = new StringTokenizer(string, ".");
String firstToken = tokenizer.nextToken();
String secondToken = tokenizer.nextToken();
As you are finding for last word CreateRequisitionRO you can also use
String testStr = "[Lcom.hexgen.ro.request.CreateRequisitionRO;";
String yourString = testStr.substring(testStr.lastIndexOf('.')+1, testStr.length()-1);
String testStr = "[Lcom.hexgen.ro.request.CreateRequisitionRO;";
String test[] = testStr.split("\\.");
for (String string : test) {
System.out.println("test : " + string);
}
System.out.println("Str Length : " + test.length);
The "." is a regular expression wildcard you need to escape it.
Change String test[] = testStr.split("."); to String test[] = testStr.split("\\.");.
As the argument to String.split takes a regex argument, you need to escape the dot character (which means wildcard in regex):
Note that String.split takes in a regular expression, and . has special meaning in regular expression (which matches any character except for line separator), so you need to escape it:
String test[] = testStr.split("\\.");
Note that you escape the . at the level of regular expression once: \., and to specify \. in a string literal, \ needs to be escaped again. So the string to pass to String.split is "\\.".
Or another way is to specify it inside a character class, where . loses it special meaning:
String test[] = testStr.split("[.]");
You need to escape the . as it is a special character, a full list of these is available. Your split line needs to be:
String test[] = testStr.split("\\.");
Split takes a regular expression as a parameter. If you want to split by the literal ".", you need to escape the dot because that is a special character in a regular expression. Try putting 2 backslashes before your dot ("\\.") - hopefully that does what you are looking for.
String test[] = testStr.split("\\.");

Manipulating IP addresses - split string on '.' character

String address = "192.168.1.1";
I want to split the address and the delimiter is the point.
So I used this code:
String [] split = address.split(".");
But it didn't work, when I used this code it works:
String [] split = address.split("\\.");
so why splitting the dot in IPv4 address is done like this : ("\\.") ?
You need to escape the "." as split takes a regex. But you also need to escape the escape as "\." won't work in a java String:
String [] split = address.split("\\.");
This is because the backslash in a java String denotes the beginning of a character literal.
You should split like this, small tip use Pattern.compile as well
String address = "192.168.1.1";
String[] split = address.split("\\.");// you can replace it with private static final Pattern.

Categories