Rasoul
Rasoul

Reputation: 187

What is the correct regex to accomplish string split in java?

I have a String "50[=]Test Item" that I want to split in java using String.split to get "50" and "Test Item". What is the correct regex to accomplish that.

Any help is appreciated.

Upvotes: 1

Views: 111

Answers (2)

RudolphEst
RudolphEst

Reputation: 1250

You have to escape the [ and ] characters since split accepts a regular expression, and not a simple string. In a regular expression, the characters [ and ] have special meaning, indicating a character class. Thus, you might want to try the following:

String[] splits = yourVar.split("\\[=\\]");

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213391

You need to escape [, while splitting, as it is special character in regex. You just need to escape [ because it starts a character class. No need to escape ]:

Arrays.toString("50[=]Test Item".split("\\[=]"));

will give you:

[50, Test Item]

Upvotes: 6

Related Questions