192.168.0.1 까지 가는 경로를 보여준다.
ping 192.168.0.1
Alfa (알파)
Bravo(브라보)
Charlie(찰리)
Delta(델타)
Echo(에코)
Foxtrot(폭스트롯)
Golf(골프)
Hotel(호텔)
India(인디아)
Juliet(줄리엣)
Kilo(킬로)
Lima(리마)
Mike(마이크)
November(노벰버)
Osca(오스카)
Papa(파파)
Quebec(퀘벡)
Romeo(로미오)
Sierra(시에라)
Tango(탱고)
Uniform(유니폼)
Victor(빅터)
Wiskey(위스키)
X-ray(엑스레이)
Yankee(양키)
Zulu(즐루)
출처 : http://home.postech.ac.kr/%7Edada/methodx/reg_ex.html
PHP에서 정규표현식을 지원하는 함수로는 ereg(), eregi(), ereg_replace(), eregi_replace(), split(), spliti() 등이 있다. 이 때 ereg_replace 보다 preg_replace가 훨씬 빠르다고 한다.
이 외에도 펄 형식을 지원하는 정규표현식에 관련된 함수들도 있다.
First of all, let's take a look at two special symbols: '^ (start)' and '$ (end)'.
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.
You can also use bounds, which come inside braces and indicate ranges in the number of occurences:
Now, to quantify a sequence of characters, put them inside parentheses:
There's also the '|' symbol, which works as an OR operator:
A period ('.') stands for any single character:
Bracket expressions specify which characters are allowed in a single position of a string:
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).
\ 는 특수 문자를 문자 자체로 해석하도록 하는 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 등도 찾게 된다.
특수문자가 [] 안과 밖에서 다르다는 점을 생각하여 각각의 경우를 살펴보자. 우선 [] 밖의 경우는,
첫번째 방법은 보통 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의 예
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.
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주소의 형식은 www.aaa.net 과 같으며 영숫자 . \ ? & _ = ~ + 등으로 이루어져 있다.
[0-9a-zA-Z_]+(\.[0-9a-zA-Z/\?_=+~]+)*
(http|ftp|https):/{2}[0-9a-zA-Z_]+(\.[0-9a-zA-Z/\?_=+~]+)*
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; }
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];
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>
이 된다.
Now here's something to make you busy:
다음의 문서들을 참고했습니다.
[1] Learning to Use Regular Expressions by Example by Dario F. Gomes
[2] 전정호님의 정규표현식 기초 ( http://www.whiterabbitpress.com/osp/unix/regex.html )
[3] 모두랑의PHP 따라잡기 게시물 ( http://modulang.net/board/view_study.php?code=class&mode=view&no=13 )