Eclipse IDE Tool 2009. 2. 6. 14:15

이클립스에서 정규식 사용하기

 

a?  a가 0개 혹은 1개 발생하면 일치  'a' 나 빈 문자열
a*  a가 0 혹은 그 이상 발생할 때 일치  빈 문자열이나 'a', 'aa', 'aaa', 등
a+  a가 1번 이상 발생하면 일치 'a', 'aa', 'aaa', 등 
a|b  a 나 b면 일치 'a' 나 'b'
.  한개의 문자면 일치  'a', 'q', 'l', '_', '+', 등
[woeirjsd]  지정한 문자들 중 하나 이면 일치  'w', 'o', 'e', 'i', 'r', 'j', 's', 'd' 
[1-9]  범위 안의 문자면 일치  '1', '2', '3', '4', '5', '6', '7', '8', '9' 
[^13579]  지정한 문자 이외의 문자이면 일치  짝수 혹은 문자 
(ie)  수식을 묶음 (다른 연산자와 사용하기 위함)  'ie' 
^a  줄의 맨 처음에 a가 있으면 일치 'a' 
a$  줄의 맨 끝에 a가 있으면 일치  'a' 


ex>

a(.*)b : a다음에 어떤한 글자가 와도 된다.   
  일치단어 : acvcvb, ab, ab343bkkk


정규표현식 (Regular Expressions)

PHP에서 정규표현식을 지원하는 함수로는 ereg(), eregi(), ereg_replace(), eregi_replace(), split(), spliti() 등이 있다. 이 때 ereg_replace 보다 preg_replace가 훨씬 빠르다고 한다.
이 외에도 펄 형식을 지원하는 정규표현식에 관련된 함수들도 있다.

1. 기초 (Basic Syntax)

First of all, let's take a look at two special symbols: '^ (start)' and '$ (end)'.

  • "^The": matches any string that starts with "The";
  • "of despair$": matches a string that ends in the substring "of despair";
  • "^abc$": a string that starts and ends with "abc" -- that could only be "abc" itself!
  • "notice": a string that has the text "notice" in it. "notice" 그 자체가 아닌 "notice"를 포함하는 것을 뜻한다.

There are also the symbols '* (zero or more)', '+ (one or more)', and '? (zero or one)', which denote the number of times a character or a sequence of characters may occur.

  • "ab*": matches a string that has an a followed by zero or more b's ("a", "ab", "abbb", etc.);
  • "ab+": same, but there's at least one b ("ab", "abbb", etc.);
  • "ab?": there might be a b or not;
  • "a?b+$": a possible a followed by one or more b's ending a string.

You can also use bounds, which come inside braces and indicate ranges in the number of occurences:

  • "ab{2}": matches a string that has an a followed by exactly two b's ("abb");
  • "ab{2,}": there are at least two b's ("abb", "abbbb", etc.);
  • "ab{3,5}": from three to five b's ("abbb", "abbbb", or "abbbbb").
  • "ab{0,}" → "ab*"
  • "ab{1,}" → "ab+"
  • "ab{0,1}" → "ab?"

Now, to quantify a sequence of characters, put them inside parentheses:

  • "a(xxyy)*": matches a string that has an a followed by zero or more copies of the sequence "xxyy";
  • "a(bc){1,5}": one through five copies of "bc."; ("abc", "abcbc" , "abcbcbc", "abcbcbcbc", or "abcbcbcbcbc")

There's also the '|' symbol, which works as an OR operator:

  • "hi|hello": matches a string that has either "hi" or "hello" in it;
  • "(b|cd)ef": a string that has either "bef" or "cdef";
  • "(a|b)*c": a string that has a sequence of alternating a's and b's ending in a c; ("ac", "bc", or "c")

A period ('.') stands for any single character:

  • "a.[0-9]": matches a string that has an a followed by one character and a digit; ("ax1", "ak7", etc.)
  • "^.{3}$": a string with exactly 3 characters.
  • "^(100)(\.[0-9]{1,2})?$" : "100"이거나 100 다음에 소수점이 있다면 첫째나 둘째자리까지 있다.

Bracket expressions specify which characters are allowed in a single position of a string:

  • "[ab]": matches a string that has either an a or a b (that's the same as "a|b");
  • "[a-d]": a string that has lowercase letters 'a' through 'd' (that's equal to "a|b|c|d" and even "[abcd]");
  • "^[a-zA-Z]": a string that starts with a letter;
  • "[0-9]%": a string that has a single digit before a percent sign;
  • ",[a-zA-Z0-9]$": a string that ends in a comma followed by an alphanumeric character.

You can also list which characters you DON'T want -- just use a '^' as the first symbol in a bracket expression (i.e., "%[^a-zA-Z]%" matches a string with a character that is not a letter between two percent signs).

  • "[^abc]": a, b, 또는 c를 제외한 문자.
  • "[^0-9]: 숫자를 제외한 문자.

특수문자에 해당하는 문자 사용하기

\ 는 특수 문자를 문자 자체로 해석하도록 하는 Escape 문자로 사용된다. ? 자체를 찾으려고 하면 \? 와 같이 사용되어야 한다.
\ 를 사용해야 하는 문자로는 ^ \ | [] () {} . * ? + 가 있다. 이 문자들을 문자 자체로 해석을 하기위해서는
\^ \\ \| \[ \( \{ \. \* \? \+ 등과 같이 사용해야 한다.

In order to be taken literally, you must escape the characters "^.[$()|*+?{\" with a backslash ('\'), as they have special meaning.
On top of that, you must escape the backslash character itself in PHP3 strings, so, for instance, the regular expression "(\$|?[0-9]+" would have the function call: ereg("(\\$|?[0-9]+", $str) (what string does that validate?)

Just don't forget that bracket expressions are an exception to that rule--inside them, all special characters, including the backslash ('\'), lose their special powers (i.e., "[*\+?{}.]" matches exactly any of the characters inside the brackets). And, as the regex man pages tell us: "To include a literal ']' in the list, make it the first character (following a possible '^'). To include a literal '-', make it the first or last character, or the second endpoint of a range."

예를 들어 what?이라는 물음표로 끝나는 문자를 찾고 싶다고, egrep 'what?' ...이라고 하면 ?이 특수문자이므로 wha를 포함한 whale도 찾게 된다. 또, 3.14로 찾을때는 3+14 등도 찾게 된다.

특수문자가 [] 안과 밖에서 다르다는 점을 생각하여 각각의 경우를 살펴보자. 우선 [] 밖의 경우는,

  • \을 특수문자 앞에 붙이기. 예, "what\?", "3\.14"
  • []을 사용하기. 예, "what[?]", "3[.]14"

첫번째 방법은 보통 escape라고 부르며, 특수문자 앞에 \을 붙여서 특수문자의 특수한 기능을 제거한다. 두번째 방법은 [] 밖의 많은 특수문자들이 [] 안에서는 일반문자가 되는 점을 이용한 것이다. 보통 첫번째 방법을 많이 사용한다.
이 때 \도 뒤에 나오는 특수문자를 일반문자로 만드는 특수문자이기 때문에, 문자 그대로의 \을 나타내려면 \\을 사용해야 한다. 물론 [\]도 가능하다.

[] 안의 특수문자는 위치를 바꿔서 처리한다. 먼저, ^는 [^abc]와 같이 처음에 나와야만 의미가 있으므로 [abc^]와 같이 다른 위치에 사용하면 된다. -는 [a-z]와 같이 두 문자 사이에서만 의미가 있으므로 [-abc]나 [abc-]와 같이 제일 처음이나 마지막에 사용한다. (grep과 같이 도구에 따라 역으로 일반 문자앞에 \를 붙여서 특수문자를 만드는 경우가 있다.)

For completeness, I should mention that there are also collating sequences, character classes, and equivalence classes. I won't be getting into details on those, as they won't be necessary for what we'll need further down this article. You should refer to the regex man pages for more information.

character class의 예

  • [[:alpha:]][a-zA-Z]
  • [[:digit:]][0-9]
  • [[:alnum:]][0-9a-zA-Z]
  • [[:space:]]공백문자

 

2. 응용 예제

lidating Money Strings

Ok, we can now use what we've learned to work on something useful: a regular expression to check user input of an amount of money. A quantity of money can be written in four ways we can consider acceptable: "10000.00" and "10,000.00", and, without the cents, "10000" and "10,000". Let's begin with:

^[1-9][0-9]*$

That validates any number that doesn't start with a 0. But that also means the string "0" doesn't pass the test. Here's a solution:

^(0|[1-9][0-9]*)$

"Just a zero OR some number that doesn't start with a zero." We may also allow a minus sign to be placed before the number:

^(0|-?[1-9][0-9]*)$

That means: "a zero OR a possible minus sign and a number that doesn't start with a zero." Ok, let's not be so strict and let the user start the number with a zero. Let's also drop the minus sign, as we won't be needing it for the money string. What we could do is specify an optional decimal fraction part in the number:

^[0-9]+(\.[0-9]+)?$

It's implicit in the highlited construct that a period always comes with at least one digit, as a whole set. So, for instance, "10." is not validated, whereas "10" and "10.2" are.

^[0-9]+(\.[0-9]{2})?$

We specified that there must be exactly two decimal places. If you think that's too harsh, you can do the following:

^[0-9]+(\.[0-9]{1,2})?$

That allows the user to write just one number after the period. Now, as for the commas separating the thousands, we can put in:

^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]{1,2})?$

"A set of 1 to 3 digits followed by zero or more sets of a comma and three digits." Easy enough, isn't it? But let's make the commas optional:

^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(\.[0-9]{1,2})?$

That's it. Don't forget that the '+' can be substituted by a '*' if you want empty strings to be accepted also (why?). And don't forget to escape the backslash for the function call (common mistake here). Now, once the string is validated, we strip off any commas with str_replace(",", "", $money) and typecast it to double so we can make math with it.

 

Validating E-mail Addresses

Ok, let's take on e-mail addresses. There are three parts in an e-mail address: the POP3 user name (everything to the left of the '@'), the '@', and the server name (the rest). The user name may contain upper or lowercase letters, digits, periods ('.'), minus signs ('-'), and underscore signs ('_'). That's also the case for the server name, except for underscore signs, which may not occur.

Now, you can't start or end a user name with a period, it doesn't seem reasonable. The same goes for the domain name. And you can't have two consecutive periods, there should be at least one other character between them. Let's see how we would write an expression to validate the user name part:

^[_a-zA-Z0-9-]+$

That doesn't allow a period yet. Let's change it:

^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*$

That says: "at least one valid character followed by zero or more sets consisting of a period and one or more valid characters."

To simplify things a bit, we can use the expression above with eregi(), instead of ereg(). Because eregi() is not sensitive to case, we don't have to specify both ranges "a-z" and "A-Z" -- one of them is enough:

^[_a-z0-9-]+(\.[_a-z0-9-]+)*$

For the server name it's the same, but without the underscores:

^[a-z0-9-]+(\.[a-z0-9-]+)*$

Done. Now, joining both expressions around the 'at' sign, we get:

^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$

Microsoft .NET framework의 RegularExpressionValidate 컨트롤에서는
^[_a-zA-Z0-9]+([-+.][_a-zA-Z0-9]+)*@[_a-zA-Z0-9]+([-.][_a-zA-Z0-9]+)*\.[_a-zA-Z0-9]+([-.][_a-zA-Z0-9]+)*$
이렇게 쓰고있다. 이게 더 정확한 듯 하다. 위의 것은 '-'으로 시작하는 것을 허용하는데 이것은 그렇지 않다.

 

주민등록번호

주민등록번호는 "6자리의 숫자 - (1|2|3|4)로 시작하는 7자리의 숫자" 의 형태로 되어있다.

[0-9]{6}-(1|2|3|4)[0-9]{6}

 

자연수 및 유리수

<script language="javascript">
<!--
function realCheck(Str) {
      var fooPat=/^[1-9][0-9]*(\.[0-9]+)?$/
      var matchArray=Str.match(fooPat)
      if (matchArray==null) {return false;}
      return true;
}

function positiveIntCheck(Str) {
      var fooPat=/^[1-9][0-9]*$/
      var matchArray=Str.match(fooPat)
      if (matchArray==null) {return false;}
      return true;
}
//-->
</script>

 

URL 주소

URL주소의 형식은 www.aaa.net 과 같으며 영숫자 . \ ? & _ = ~ + 등으로 이루어져 있다.

[0-9a-zA-Z_]+(\.[0-9a-zA-Z/\?_=+~]+)*

(http|ftp|https):/{2}[0-9a-zA-Z_]+(\.[0-9a-zA-Z/\?_=+~]+)*

 

E-mail 기타 등등


if(!eregi("^([[:alnum:]_%+=.-]+)@([[:alnum:]_.-]+)\.([a-z]{2,3}|[0-9]{1,3})$",$email)) 
{ 
    echo "잘못된 email address 다.";  
} 

if(!ereg("([^[:space:]])",$name)) {
echo("<script>alert('이름을 입력하세요!');history.go(-1)</script>");
exit;
}

if(!ereg("([a-zA-Z0-9]+)@([a-zA-Z0-9])([.a-zA-Z0-9]+)([a-zA-Z0-9])$",$email)) {
echo("<script>alert('올바른 E-Mail 주소가 아닙니다.');history.go(-1)</script>");
exit;
}

if(!ereg("(^[0-9a-zA-Z]{4,8}$)",$passwd)) {
echo("<script>alert('비밀번호는 4자에서 8자까지의 영문자 또는 숫자로 입력하세요!');history.go(-1)
</script>");
exit;
}

if(!ereg("([^[:space:]])",$title)) {
echo("<script>alert('제목을 입력하세요!');history.go(-1)</script>");
exit;
}

 

Other uses

Extracting Parts of a String

ereg() and eregi() have a feature that allows us to extract matches of patterns from strings (read the manual for details on how to use that). For instance, say we want do get the filename from a path/URL string -- this code would be all we need:

ereg("([^\\/]*)$", $pathOrUrl, $regs);
echo $regs[1];

Advanced Replacing

ereg_replace() and eregi_replace() are also very useful: suppose we want to separate all words in a string by commas:

ereg_replace("[ \n\r\t]+", ",", trim($str));

 

찾은문자열 사용하기

정규식을 이용하여 문자열을 찾는 함수는 ereg()와 eregi() 함수이다. 이 함수 문자열에서 찾고자 하는 문자의 패턴이 있는지 확인할 수 있다. 그런데 문자열이 존재하는지 확인만하고 어떤 문자열을 찾았는지 볼수 있는 방법은 없을까?
ereg("a(b*)(c+)", "abbbbcccd", $reg);
다음과 같이 세번째 인자를 주면 주어진 패턴과 일치하는 문자열을 구할수 있다. 그럼 $reg 에는 어떤것들이 저장되어있을까 ? $reg는 배열의 형태로 반환이 된다.
$reg[0] 에는 주어진 전체 패턴인 a(b*)(c+)에 대한 내용이 들어간다. 위의 함수 결과에서는 abbbbccc 가 된다.
$reg[1]에는 첫 번째 (b*) 에 해당하는 bbbb가 들어간다.
$reg[2]에는 두 번째 ()인 (c+) 에 해당하는 ccc가 들어가게 된다.
그러면 ()안에 또 ()가 들어가면 어떤 식으로 해석이 될까?
만약에 (a+(a*))a(b+(c*))라는 패턴이 있으면 어떤 식으로 들어가게 될 지를 알아보자.
먼저 $reg[0]에는 전체 패턴인 (a+(a*))a(b+(c*))에 대한 내용이 들어간다.
$reg[1]에는 첫 번째 큰 ()인 (a+(a*)) 에 대한 내용이 들어가고, $reg[2] 에는 이 괄호 안에 있는 작은 괄호 (a*) 에 대한 내용이 들어간다. $reg[3], $reg[4] 에는 각각 (b+(c*)), (c*)의 내용이 들어가게 된다.

 

정규식을 이용한 문자열 치환

정규 표현식을 이용하여 문자열을 치환하는 함수는 ereg_replace()와 eregi_replace() 함수가 있다.
두 함수의 차이점은 eregi_replace()의 경우에는 영문자의 대소문자 구분을 하지 않는것이다.

$str = "test test"; // 두 개의 test 사이에는 4개의 스페이스가 있다.
&str = ereg_replace(" "," ", $str);
이 명령의 실행결과로 $str = "test test"; 가 된다.
이는 내용을 출력할 때 많이 사용되는 구문이다. 그럼 문자열 치환시에 문자열 패턴을 사용할 경우 찾아낸 문자열들을 다시 사용할 방법은 어떤 것이 있는가?
이럴 때 사용되는 것들이 \\0, \\1, \\2, ... 등이다.
다음과 같은 패턴이 있다고 하자.
([_0-9a-zA-Z]+(\.[_0-9a-zA-Z]+)*)@([0-9a-zA-Z]+(\.[0-9a-zA-Z]+)*)
이런 패턴이 있을 경우 전체가 \\0이 된다.
\\1([_0-9a-zA-Z]+(\.[_0-9a-zA-Z]+)*) 이 된다. \\2\.[_0-9a-zA-Z]+)이 된다. \\3([0-9a-zA-Z]+(\.[0-9a-zA-Z]+)*) 이 되고 \\4(\.[0-9a-zA-Z]+)이 된다.
다음과 같은 구문이 있을 경우:

$mail = "abc@abc.net";
$pattern = "([_0-9a-zA-Z]+(\.[_0-9a-zA-Z]+)*)@([0-9a-zA-Z]+(\.[0-9a-zA-Z]+)*)";
$link = ereg_replace($pattern, "<a href = 'mailto:\\0'>\\0</a>",$mail);

결과는 <a href='mailto:abc@abc.net'>abc@abc.net</a>
이 된다.

 

Some exercises

Now here's something to make you busy:

  • modify our e-mail-validating regular expression to force the server name part to consist of at least two names (hint: only one character needs to be changed);
  • build a function call to ereg_replace() that emulates trim();
  • make up another function call to ereg_replace() that escapes the characters '#', '@', '&', and '%' of a string with a '~'.