Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바에서 문자열이 영숫자인지 확인하는 프로그램

숫자와 알파벳 문자가 함께 포함된 단어를 영숫자(alphanumeric)라고 합니다. 자바에서는 정규 표현식을 활용해 문자열이 영숫자인지 손쉽게 판별할 수 있습니다.

다음 정규 표현식은 알파벳 대소문자와 숫자의 조합으로만 이루어진 문자열을 매칭합니다.

"^[a-zA-Z0-9]+$";

String 클래스의 matches() 메서드는 정규 표현식(문자열 형태)을 인수로 받아 현재 문자열과 비교합니다. 문자열이 해당 패턴과 일치하면 true를 반환하고, 일치하지 않으면 false를 반환합니다.

확인 절차

특정 문자열이 영숫자인지 확인하려면 다음 단계를 따릅니다.

  • 대상 문자열을 입력받습니다.
  • 위에서 소개한 정규 표현식을 인수로 전달하며 matches() 메서드를 호출합니다.
  • 반환된 결과를 확인합니다.

예제 1: matches() 메서드 사용

import java.util.Scanner;
public class AlphanumericString {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.next();
      String regex = "^[a-zA-Z0-9]+$";
      boolean result = input.matches(regex);
      if(result) {
         System.out.println("Given string is alpha numeric");
      } else {
         System.out.println("Given string is not alpha numeric");
      }
   }
}

실행 결과

Enter input string:
abc123*
Given string is not alpha numeric

입력값에 특수 문자(*)가 포함되어 있으므로 영숫자가 아니라고 판단됩니다.

예제 2: java.util.regex 패키지 사용

java.util.regex 패키지의 클래스와 메서드(API)를 사용하면 정규 표현식을 컴파일한 뒤 특정 문자열과 매칭할 수도 있습니다. 다음 프로그램은 이러한 API를 활용해 입력받은 문장을 공백 기준으로 나누고, 각 단어가 영숫자인지 개별적으로 검증합니다.

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string: ");
      String input = sc.nextLine();
      String regex = "^[a-zA-Z0-9]+$";
      String data[] = input.split(" ");
      //패턴 객체 생성
      Pattern pattern = Pattern.compile(regex);
      for (String ele : data){
         //매처 객체 생성
         Matcher matcher = pattern.matcher(ele);
         if(matcher.matches()) {
            System.out.println("The word "+ele+": is alpha numeric");
         } else {
            System.out.println("The word "+ele+": is not alpha numeric");
         }
      }
   }
}

실행 결과

Enter input string:
hello* this$ is sample text
The word hello*: is not alpha numeric
The word this$: is not alpha numeric
The word is: is alpha numeric
The word sample: is alpha numeric
The word text: is alpha numeric

실행 결과에서 볼 수 있듯이 특수 문자가 포함된 단어(hello*, this$)는 영숫자가 아니며, 알파벳으로만 구성된 단어(is, sample, text)는 영숫자로 판별됩니다. 이처럼 정규 표현식을 활용하면 입력 데이터의 유효성 검사를 간편하게 처리할 수 있습니다.