简体   繁体   中英

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")将产生{"abc", "ghi"}

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+ )

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

\\ Q和\\ E为您转义了元字符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM