Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.split() *not* on regular expression?

Tags:

java

regex

Since String.split() works with regular expressions, this snippet:

String s = "str?str?argh"; s.split("r?"); 

... yields: [, s, t, , ?, s, t, , ?, a, , g, h]

What's the most elegant way to split this String on the r? sequence so that it produces [st, st, argh]?

EDIT: I know that I can escape the problematic ?. The trouble is I don't know the delimiter offhand and I don't feel like working this around by writing an escapeGenericRegex() function.

like image 685
Konrad Garus Avatar asked Jun 16 '11 15:06

Konrad Garus


People also ask

What does * do in regular expression?

The Match-zero-or-more Operator ( * ) This operator repeats the smallest possible preceding regular expression as many times as necessary (including zero) to match the pattern.

Can we use regex in split a string?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

How do you split a string by the occurrences of a regex pattern?

Introduction to the Python regex split() function The built-in re module provides you with the split() function that splits a string by the matches of a regular expression. In this syntax: pattern is a regular expression whose matches will be used as separators for splitting. string is an input string to split.

What is split () function in string?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

A general solution using just Java SE APIs is:

String separator = ... s.split(Pattern.quote(separator)); 

The quote method returns a regex that will match the argument string as a literal.

like image 147
Stephen C Avatar answered Sep 20 '22 12:09

Stephen C


You can use

StringUtils.split("?r") 

from commons-lang.

like image 44
BastiS Avatar answered Sep 22 '22 12:09

BastiS