Search in String

Asked

Viewed 184 times

8

I have a String of dynamic size and I need to search for the "#" cross to the next blank.

I tried to use split, but without success.

String texto = "oi tudo bem como vai #01?";
String[] t ;
t = texto.split(texto);
  • 1

    You want to capture the text #01??

  • Are you sure you just want to find it? I ask because if you want to create a text replacement mechanism to put on screens, reports, etc., it would be better not to reinvent the wheel, because there are several excellent mechanisms for this.

  • Voce must use regex the documentation is very simple https://docs.oracle.com/javase/tutorial/essential/regex/ and this site has great tutorials and examples http://www.regular-expressions.info/

3 answers

8


An example of how to separate snippets starting with # and even find a blank:

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));
        }
    }
}

Upshot:

#1234a
#sdf
#$%¨#@)~

See working on Ideone

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));
    }
}

Functioning in the Ideone

2

You can do it like 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 is not seared, so be sure to treat that as well.

  • You could at least check primeiroSplit.length() to deal with the common case; it would be even better to create a List<String> to contain instances of terms introduced by wire fence. It costs no more than three more lines...

Browser other questions tagged

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