开发者

java string.split() regex help

If I have a variable string which stores a different section of characters from a larger string, how can I split the larger string aroung the smaller string using the split command with regex?

For example the string variable may store "def" The larger string may be "abcdefghi"

When the split command is preformed with the regex input as the string variable, the resulting split will be like this:

abc ghi

edit: here is the code

String string = new String("2+22*5-1*2");
String multiply = new String("22*5");

int leftNum = Integer开发者_开发百科.parseInt(multiply.split("\\*")[0]);
int rightNum = Integer.parseInt(multiply.split("\\*")[1]);

System.out.println(string);
System.out.println(multiply);
System.out.println(leftNum * rightNum);

//the following should print "2+"
String left = string.split(multiply)[0];
System.out.println(left);


"abcdefghi".split("def") will yield {"abc", "ghi"}.


string.split("\\Q" + substring + "\\E");

The \Q and \E escape out metacharacters for you.


You'll have to escape the * to use the content of multiply as a regexp (the parameter of split is a regular expression):

 String regexp = multiply.replace("*", "\\*");
 String left = string.split(regexp)[0];

This should print the expected result (2+)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜