简体   繁体   中英

Java string splitting with '?' character using regex

I want to split the following string:

"select ?1 from students in ?2"

I want to split it so that it becomes an array ["select", "from students in"] , how do I achieve this? I've tried str.split("[?\\\d]") , but this splits the string whenever it encounters '?'or a digit, but I wanted '?' and the digit to be treated as a single string

Don't surround it in [] :

str.split("\\?\\d")

If you need to experiment, there are all sorts of online sites to test your regex. The first one that showed up in a search for me today is https://regex101.com/

You are using a character class [?\\d] which matches either a backslash or a question mark.

If you don't want the spaces in the output, you can match optional leading and trailing horizontal whitespace characters, and match a question mark followed by 1 or more digits.

\h*\?\d+\h*

Regex demo | Java demo

String regex = "\\h*\\?\\d+\\h*";
String string = "select ?1 from students in ?2";
System.out.println((Arrays.toString(string.split(regex))));

Output

[select, from students in]

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