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
CodePudding user response:
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/
CodePudding user response:
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*
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]