Home > other >  how to write regex to extract numbers from a string in Java?
how to write regex to extract numbers from a string in Java?

Time:09-16

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

CodePudding user response:

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.

CodePudding user response:

You can replace the while(m.find()) with the follwing block:

m.find();
System.out.println(m.group(0));
System.out.println(m.group(1));

or pass the 0 index to the line

String xxx = m.group(0);

CodePudding user response:

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