-2

For example, I have a set of text "1234568asdjhgsd", I just want to get the number, what should I do? The following is my code, he can't execute it to the while step

    textView.setText("1234568asdjhgsd");

        String str = (String) textView.getText();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Pattern p;
                p = Pattern.compile("\\d{10}");
                Matcher m;
                m = p.matcher(str);
                
                while (m.find()){
                    String xxx = m.group();
                    System.out.println(xxx);
                }
            }
        });

It didn't print anything

Farhad
  • 12,178
  • 5
  • 32
  • 60
Luxira
  • 23
  • 3

3 Answers3

1

p = Pattern.compile("\\d{10}"); this matches 10 digits but your text "1234568asdjhgsd" only has 7 digits. You can use Pattern.compile("\\d{7}"); and it'll work. But number of digits always has to be <= 7.

KavG
  • 169
  • 1
  • 12
0

print it if matches digits.

  String str = "1234568asdjhgsd"; 
  Pattern p;
  p = Pattern.compile("\\d");
  Matcher m;
  m = p.matcher(str);
        
  while (m.find()){
      String xxx = m.group();
      System.out.print(xxx);
  }
chanrlc
  • 182
  • 1
  • 10
0

you can just use java method replaceAll with regex. This will look like this:

String someString = "1234568asdjhgsd";
String replacedString = someString.replaceAll("0-9","");

First argumen of replaceAll means it will accept only digits from 0 to 9, and the second is for what it will be changed