java

Java Regular Expression

· John Doe

672 Views

Removing everything but numbers from String

String value = string.replaceAll("[^0-9]","");
String clean1 = string1.replaceAll("[^0-9]", "");

or

String clean2 = string2.replaceAll("[^\\d]", "");

Where \d is a shortcut to [0-9] character class, or

String clean3 = string1.replaceAll("\\D", "");

Where \D is a negation of the \d class (which means [^0-9])

 

Using Match, Pattern class in java.util.regex

boolean bln = Pattern.matches("^[a-zA-Z0-9]*$", this.input);

^ : 문자열의 시작
$ : 문자열의 종료
. : 임의의 한 문자(문자의 종류는 가리지 않음)
| : or
? : 앞 문자가 없거나 하나있음.
+ : 앞 문자가 하나 이상임.
* : 앞 문자가 없을 수도 무한정 많을 수도 있음을 나타냄.
만약, .* 으로 정규식이 시작한다면 시작하는 문자열과 같은 문자열이 뒤에 없거나 많을 수도 있는 경우에만 일치를 시킨다. 즉, abc 일 경우 시작문자인 a를 기준으로 a가 없을경우와 a가 무한정 많은 경우에도 true를 반환하기 때문에 abc의 경우는 true를 반환한다.
[] : 문자 클래스를 지정할 때 사용. 문자의 집합이나 범위를 나타내면 두 문자 사이는 '-' 기호로 범위를 나타낸다. []내에서 ^ 가 선행하여 나타나면 not를 나타낸다.
{} : 선행문자가 나타나는 횟수 또는 범위
a{3} 인 경우 a가 3번 반복된 경우 / a{3,}이면 a가 3번 이상 반복인 경우. 또한 a{3,5}인 경우 a가 3번 이상 5번 이하 반복된 경우를 나타냄
\w : 알파벳이나 숫자
\W : 알파벳이나 숫자를 제외한 문자
\d : 숫자 [0-9]와 동일
\D : 숫자를 제외한 모든 문자

^[0-9]*$ : only number
^[a-zA-Z]*$ : only English
^[가-힣]*$ : only Korean
^[a-zA-Z0-9]*$ : English/number

 

e.g.

1)

email : ^[a-zA-Z0-9]+@[a-zA-Z0-9]+$  or  ^[_0-9a-zA-Z-]+@[0-9a-zA-Z-]+(.[_0-9a-zA-Z-]+)*$
cellphone :  ^01(?:0|1|[6-9]) - (?:\d{3}|\d{4}) - \d{4}$
phone : ^\d{2,3} - \d{3,4} - \d{4}$
id : \d{6} \- [1-4]\d{6}
IP addr : ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3})

https://stackoverflow.com/questions/6883579/java-regular-expression-removing-everything-but-numbers-from-string

 

2) How to test if a String contains both letters and numbers

.matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$")

The regex asserts that there is an uppercase alphabetical character (?=.*[A-Z]) somewhere in the string, and asserts that there is a digit (?=.*[0-9]) somewhere in the string, and then it checks whether everything is either alphabetical character or digit.

 

3) How can I de-duplicate repeated characters in a Java string?

how________are_______you to how_are_you

string.replaceAll("_+", "_")

 

regex