IDE Tips / How to do?

1

I have the following problem

I have some text that will be inserted by the user and we will take as an example

Implemented phrase: I would like to know how to program better #hoje.

I wanted to loop through words beginning with # a listview underneath these words (ex: #hoje) and that these should be replaced by suggestions in this listview?

How do I? Thank you in advance.

    
asked by anonymous 09.07.2018 / 22:35

1 answer

2

By using the tag I believe your difficulty is to change the #nome of the string, in your case I think this will solve:

foobar.replaceAll("(^|\s)#hoje($|\s)", "$1" + valorAtual + "$2");
  

Note: I tested \b instead of (^|\s) and ($|\s) , but I do not know why it did not work.

In a simple example it would look something like:

final String frasePadrao = "Eu gostaria de saber programar melhor #hoje";
final String fraseRegex = "(^|\s)#hoje($|\s)";

listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>()
{
    @Override
    public void changed(ObservableValue<? extends String> observable, String valorAntigo, String valorAtual)
    {
        minhaLabel.setText(
           frasePadrao.replaceAll(fraseRegex, "$1" + valorAtual + "$2")
        );
    }
});
  

minhaLabel would be a label where text appears

Explaining the regex

  • (^|\s) search for space or beginning of string
  • #hoje fetches the word you'd like to be replaced
  • ($|\s) search space or end of string

That is, in this way you can write #hoje to any position in the string, avoiding conflict with other texts that could vary. Technically \b should resolve this from the spaces between the word, but I do not know if it's a Java behavior, it just does not work:

 "\b#hoje\b"

In other languages I had no problem using \b . However, (^|\s) and ($|\s) already meet this

    
09.07.2018 / 23:20