membersound
membersound

Reputation: 86925

How to create a regex pattern for splitting at specific chars?

I want to create a Splitter (guava) and split a string based on a regex pattern. The split should take place either on [ or on .. character. And what if I want to include eg 10 characters for a split? Would I have to separate each of them by | in the regex?

But the following does not work: Pattern.compile("[|..")

Test: test[me..once more should result in

test
me
once more

Upvotes: 1

Views: 47

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627535

You can use the following regex to split:

(?:\[|\.\.)

In Java, you will have to escape the \s.

String str = "test[me..once more";
String pattern = "(?:\\[|\\.\\.)";
String[] parts = str.split(pattern);

Upvotes: 4

Dragondraikk
Dragondraikk

Reputation: 1679

Your pattern does not work because [ and . are control characters in regexes.

try escaping them like Pattern.compile("\\[|\\.\\.") (remember, \ also needs to be escaped)

Upvotes: 0

Related Questions