Separate strings by semicolon but also store the semicolon

Asked

Viewed 1,054 times

0

I am using the split to separate strings by space, enter and semicolon, but when it is the semicolon I need to store it in an array position as well. How to do this?

Current Code:

String[] textoSeparado = texto.split(" |\\n|;");
  • 1

    It is not clear what you want. Put an input example and an output example. Also, your question is not related to Android (or Android Studio), only to Java. I’m removing the tags.

1 answer

3


After reading a few times, I think I understand what you mean:

separate a string using space(" "), line break( n or r) and point and comma(;) as delimiters, but including the ; as a list item.

If I’m right, I was able to arrange a regex that met those conditions, and the result was:

String[] stringSeparada = teste.split("((?<=;)|(?=;))|\\s");

See the test below:

//dois exemplos com ambos os tipos de quebras de linhas(windows/linux)
String teste = ";espaco pontoevirgula;QUEBRA\ndelinha;";
String teste2 = ";espaco pontoevirgula;QUEBRA\rdelinha;";
String regex = "((?<=;)|(?=;))|\\s";

String[] stringSeparada = teste.split(regex);
String[] stringSeparada2 = teste2.split(regex);

System.out.println(Arrays.toString(stringSeparada));
System.out.println(Arrays.toString(stringSeparada2));

Exit:

[;, twilight, twisting, twisting, twisting, twisting, twisting, ;]
[;, twilight, twisting, twisting, twisting, twisting, twisting, ;]

Note that regex will capture the ; no matter where she appears.

See working online on IDEONE.


References:

  • Thank you, that’s exactly what it was. I don’t know much about regular expressions, so could you explain to me this piece that you created? 'Cause I’d like to add this semicolon rule to other symbols.

  • @Lucasfernando the first group checks if the semicolon is in the string , but does not consume if it is found. As for the problem reported, always prefer to comment on the answer, I will try to simulate to see how to solve.

  • @Lucasfernating the problem you reported to catch if the ; is at the end does not occur, see: https://ideone.com/SALmmy

  • https://regex101.com/r/PhCFTg/1/, just briefly summarised.

  • 2

    enjoying, now looking again you used \s and then \r\n, I think I’d better take a look at (What does the REGEX shortcut mean?)[https://answall.com/q/110701/14213]

  • 1

    @Guilhermelautert Ops! I didn’t need the \n?\r, who waved kkkk, already packed and thank you, again. :)

  • Thanks friends, the problem with the semicolon was elsewhere in my code. Now it is working properly. Thank you.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.