When I put the \\ b in the pattern.compiler it returns the find as false

1

When I put \ b in pattern.compiler it returns matcher.find as false, because it can not find a pattern just because of \ b.

Following the code I use:

final Pattern py = Pattern.compile("\b(print|True|False|int|str|float|bool)\b)");

edittext.addTextChangedListener(new TextWatcher() {
    Matcher m;
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    } 
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    } 
    @Override 
    public void afterTextChanged(Editable e) {
        m = py.matcher(e);
        while (m.find()) {
            e.setSpan(new ForegroundColorSpan(Color.WHITE),m.start() ,m.end() ,0);
        }
    }
});

But if I take the \ b works but not the way I want it.

    
asked by anonymous 06.10.2017 / 14:25

2 answers

1

I believe that you are using matcher.find in the wrong way, the value returned by this method changes at each position of the parsed string.

Your pattern is matching and finding the word print , but it still looks at the last position of the text (position signaled by the% token in that example ) and not match, changing the matcher value to $ .

So for your case the best way is to use it as a condition for a false or while that changes a boolean to true if it finds and uses that value as a condition.

import java.util.regex.*;  
public class RegexExampleMatcher{  
public static void main(String args[]){  
  boolean achou = false;
  String content = "print";                          //String analisada                    
  Pattern pattern = Pattern.compile("\bprint\b");  //String que será usada como padrão
  Matcher matcher = pattern.matcher(content);        //Matcher para usar o método find

  while(matcher.find()) {                            //Enquanto matcher.find for true
     System.out.println("Achou");                    //Imprima achou
     achou = true;                                   //muda o boolean achou para true
  }
  if (achou){
     //método que será executado
     }
}
}

You can test this example here

    
06.10.2017 / 15:36
2

Thanks @Paz for your answer but I simply use an app that it uses bars in its string: Ex:

String A = "\b";

What was actually happening was that the app would pick up a slash from the other java and would only get the b with the default string knowing that I put another slash eg:

String  a = "\\b";

It was a disrespect of mine.

    
07.10.2017 / 20:50