1. 2014.09.27 Java, Number Regular-Expression

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);

	System.out.println(text+ " is number");		
	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


'Java' 카테고리의 다른 글

Java, Number Regular-Expression  (0) 2014.09.27
Netty(java nio 통신 프레임워크) 대략적인 흐름  (0) 2014.04.15