1. Overview

  In Java, [tryParse] is not supported like c#. When String text is not number, Integer.parseInt() or Float.parseFloat() don't return false but throw exception. So developer have to make this function. One way is using Regular-Expression. 


2. Code

  Below code show Regular-Expression of getting number from String.

String text = text_field.getText();
Pattern p = Pattern.compile("-?([\\d]+)(([.]?)([\\d]+))?");
Matcher m = p.matcher(text);

if(m.matches())
{
	System.out.println(text+ " is number");		
}else
{
	System.out.println(text+ " is not number");		
}


3. Regular-Expression

-? : '-' character could be existed or not existed. Matches the preceding element zero or one time. For example, ab?c matches only "ac" or "abc".

[\d]  : 0~9 characters  

+ : Matches the preceding pattern element one or more times.

() : Groups a series of pattern elements to a single element. When you match a pattern within parentheses, you can use any of 

$1, $2, ... later to refer to the previously matched pattern.

(([.]?)([\\d]+))  : A decimal point below could be existed or not existed.


if you want to know more about regular-expression, reference wiki

 




미니난투 온라인

댓글을 달아 주세요