Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

정규식을 사용하여 문자열에서 숫자를 추출하는 방법은 무엇입니까?

<시간/>

다음 정규식 중 하나를 사용하여 주어진 문자열의 숫자를 일치시킬 수 있습니다 -

“\\d+”
Or,
"([0-9]+)"

예시 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractingDigits {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter sample text: ");
      String data = sc.nextLine();
      //Regular expression to match digits in a string
      String regex = "\\d+";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("Digits in the given string are: ");
      while(matcher.find()) {
         System.out.print(matcher.group()+" ");
      }
   }
}

출력

Enter sample text:
this is a sample 23 text 46 with 11223 numbers in it
Digits in the given string are:
23 46 11223

예시 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Just {
   public static void main(String[] args) {
      String data = "abc12def334hjdsk7438dbds3y388";
      //Regular expression to digits
      String regex = "([0-9]+)";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("Digits in the given string are: ");
      while(matcher.find()) {
         System.out.print(matcher.group()+" ");
      }
   }
}

출력

Digits in the given string are:
12 334 7438 3 388