String Search

8

I have a dynamic size String and need to search the "#" all characters until the next blank space.

I tried to use split, but without success.

String texto = "oi tudo bem como vai #01?";
String[] t ;
t = texto.split(texto);
    
asked by anonymous 18.04.2017 / 16:36

3 answers

8

An example of how to separate snippets that start with # and will even find a blank space:

import java.util.regex.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String texto = "oi tudo bem como vai #1234a #sdf #$%¨#@)~";
        Pattern p = Pattern.compile("#\S+");
        Matcher m = p.matcher(texto);
        while(m.find()) {
            System.out.println(m.group(0));
        }
    }
}

Result:

  

# 1234a
  #sdf
  Eur-lex.europa.eu eur-lex.europa.eu

See working at Ideone

    
18.04.2017 / 17:09
5

You can try with regex

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "[#]\w*\d*\W\s*";
final String string = "oi tudo bem como vai #01?";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}

Running on Ideone

    
18.04.2017 / 16:45
2

You can do this:

String cantadaHorrivel = "oi tudo bem como vai #01?";
String[] primeiroSplit = cantadaHorrivel.split("#");
String[] segundoSplit = primeiroSplit[1].split(" ");
String texto = segundoSplit[0];

This will fail if the original input has no markup, so do not forget to treat it too.

    
18.04.2017 / 16:39