String.split() using multiple character delimeter - java

I have a String saved in the database like this:
01/01/2014$%^&02/01/2014
I am using the split() java method. Here is my code:
String value = database.getValue(); // this returns the value mentioned above
String values[] = value.split("$%^&");
System.out.println("length is = " + values.length);
System.out.println(values[0]);
The Output:
length is = 1
01/01/2014$%^&02/01/2014
What am I doing wrong?

Use Pattern#quote:
String values[] = value.split(Pattern.quote("$%^&"));
What am I doing wrong?
String#split takes a regex as its argument. Some characters in your String have special meaning. In your case, you want the String representation, not regex. quote does that for you.
Alternative solutions:
Escape the special characters by \\ (Escaping regex is done by \. But in Java, \ is written \\)
Use String#replace that accepts String

You can try this too. Here we can escape special characters.
String value = "01/01/2014$%^&02/01/2014";
String values[] = value.split("\\$%\\^&");
System.out.println("length is = " + values.length);
System.out.println(values[0]);
Out put:
length is = 2
01/01/2014

Related

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 = "\\(|\\)|\"|:|;|,|\\?|!|\\."

How to replace all numbers in java string

I have string like this String s="ram123",d="ram varma656887"
I want string like ram and ram varma so how to seperate string from combined string
I am trying using regex but it is not working
PersonName.setText(cursor.getString(cursor.getColumnIndex(cursor
.getColumnName(1))).replaceAll("[^0-9]+"));
The correct RegEx for selecting all numbers would be just [0-9], you can skip the +, since you use replaceAll.
However, your usage of replaceAll is wrong, it's defined as follows: replaceAll(String regex, String replacement). The correct code in your example would be: replaceAll("[0-9]", "").
You can use the following regex: \d for representing numbers. In the regex that you use, you have a ^ which will check for any characters other than the charset 0-9
String s="ram123";
System.out.println(s);
/* You don't need the + because you are using the replaceAll method */
s = s.replaceAll("\\d", ""); // or you can also use [0-9]
System.out.println(s);
To remove the numbers, following code will do the trick.
stringname.replaceAll("[0-9]","");
Please do as follows
String name = "ram varma656887";
name = name.replaceAll("[0-9]","");
System.out.println(name);//ram varma
alternatively you can do as
String name = "ram varma656887";
name = name.replaceAll("\\d","");
System.out.println(name);//ram varma
also something like given will work for you
String given = "ram varma656887";
String[] arr = given.split("\\d");
String data = new String();
for(String x : arr){
data = data+x;
}
System.out.println(data);//ram varma
i think you missed the second argument of replace all. You need to put a empty string as argument 2 instead of actually leaving it empty.
try
replaceAll(<your regexp>,"")
you can use Java - String replaceAll() Method.
This method replaces each substring of this string that matches the given regular expression with the given replacement.
Here is the syntax of this method:
public String replaceAll(String regex, String replacement)
Here is the detail of parameters:
regex -- the regular expression to which this string is to be matched.
replacement -- the string which would replace found expression.
Return Value:
This method returns the resulting String.
for your question use this
String s = "ram123", d = "ram varma656887";
System.out.println("s" + s.replaceAll("[0-9]", ""));
System.out.println("d" + d.replaceAll("[0-9]", ""));

having trouble with arrays and maybe split

String realstring = "&&&.&&&&";
Double value = 555.55555;
String[] arraystring = realstring.split(".");
String stringvalue = String.valueof(value);
String [] valuearrayed = stringvalue.split(".");
System.out.println(arraystring[0]);
Sorry if it looks bad. Rewrote on my phone. I keep getting ArrayIndexOutOfBoundsException: 0 at the System.out.println. I have looked and can't figure it out. Thanks for the help.
split() takes a regexp as argument, not a literal string. You have to escape the dot:
string.split("\\.");
or
string.split(Pattern.quote("."));
Or you could also simply use indexOf('.') and substring() to get the two parts of your string.
And if the goal is to get the integer part of a double, you could also simply use
long truncated = (long) doubleValue;
split uses regex as parameter and in regex . means "any character except line separators", so you could expect that "a.bc".split(".") would create array of empty strings like ["","","","",""]. Only reason it is not happening is because (from split javadoc)
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
so because all strings are empty you get empty array (and that is because you see ArrayIndexOutOfBoundsException).
To turn off removal mechanism you would have to use split(regex, limit) version with negative limit.
To split on . literal you need to escape it with \. (which in Java needs to be written as "\\." because \ is also Strings metacharacter) or [.] or other regex mechanism.
Dot (.) is a special character so you need to escape it.
String realstring = "&&&.&&&&";
String[] partsOfString = realstring.split("\\.");
String part1 = partsOfString[0];
String part2 = partsOfString[1];
System.out.println(part1);
this will print expected result of
&&&
Its also handy to test if given string contains this character. You can do this by doing :
if (string.contains(".")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain .");
}

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("\\.");

How can I split a string by two delimiters?

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}

Categories