0

I've got a string in Java: Acidum acetylsalic. Acid.ascorb, Calcium which I want to split. The string has to be cut after every space preceded by a dot or colon: ,[space] or .[space]

In result I need three strings: Acidum acetylsalic, Acid.ascorb, Calcium

I know I need some regex and according to this and this I tried "\, |\. " but I doubt that's not how regex work.

Community
  • 1
  • 1
Kamil
  • 1,456
  • 4
  • 32
  • 50
  • replace all dot or commas with commas or dots then split your string – John Pangilinan Dec 29 '15 at 07:29
  • Possible duplicate of [Java Splitting a string into 2 strings based on a delimiter.](http://stackoverflow.com/questions/7631808/java-splitting-a-string-into-2-strings-based-on-a-delimiter) – NSNoob Dec 29 '15 at 08:56

4 Answers4

2

Split by

"[,.] "

[,.] - character set with one comma or dot


The problem with your original regex is that you need to escape the dot once to make it a literal dot and a second time to escape the slash escaping it. It will also work if you change it to:
", |\\. "
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
1

Try this:

str.split("[\\.,]\\s")

....

Nyavro
  • 8,806
  • 2
  • 26
  • 33
0

Use split("(\.\s)|(\,\s)")

You need to encode special characters see https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

L.S
  • 192
  • 1
  • 6
  • Hi LS include relevant data from the link to your answer because links have the tendency to change over due course of time – NSNoob Dec 29 '15 at 07:46
0

Try this

    String str="Acidum acetylsalic. Acid.ascorb, Calcium";

    String[] resStr= str.split("[.,][\\s]");

    for (String res : resStr) {

        System.out.println(res);
    }

Output :

Acidum acetylsalic
Acid.ascorb
Calcium
kswaughs
  • 2,967
  • 1
  • 17
  • 21