How to split a string into two considering end of the string with numbers (which is inside the squre brackets)

Tags: , ,



I need to split strings into two with a given separator using regex. Sample Strings and expected output as below

testnames[3] ===> testnames,3
3alpha[0] ====> 3alpha, 0
beta[4]value[2] ===> beta[4]value, 2
gama4[23] ===> gama4, 23
tama[2334] ====> tama, 2334
tes[t[ ===> No matches
try[]t ===> No matches

Each and every String should be split into two if it has numbers within the square bracket at the end of the input string.

Can anyone tell me a regex to do this?

Note: I find out the regex : "[(-?d+)]$". But this only gave me numbers inside the square bracket and not gives the rest of the string

Answer

You may use this greedy match replacement with 2 capture groups:

RegEx:

^(.*)[(d+)]

Replacement:

$1, $2

RegEx Demo

Java Code:

String repl = str.replaceFirst("^(.*)\[(\d+)\]", "$1, $2");

RegEx Explained:

  • ^: Start
  • (.*): Greedily match 0 or more of any characters in capture group #1
  • [: Match a [
  • (d+): Match 1 or more of digits in capture group #2
  • ]: Match a ]


Source: stackoverflow