JavaScript 정규식

입력 유효성 검사 및 파일 구문 분석과 관련하여 정규식을 사용하여 수행할 수 있는 작업은 다양합니다. 가장 일반적인 식 중 일부는 사용할 수 있는 기능 및 옵션으로 인해 기억하기 어려운 경우가 많습니다. 다음은 일반적으로 사용되는 정규식 목록입니다.

사회 보장 번호\d{3}-\d{2}-\d{4}
미국 전화 번호((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}
미국 우편 번호\d{5}(-\d{4})?
인터넷 전자 메일 주소[\w-]+@([\w-]+\.)+[\w-]+
인터넷 URLhttp://([\w-]\.)+[\w-](/[\w- ./?%=]*)?
단순 암호(숫자)^(?=.*\d).{4,8}$
고급 암호(대문자, 소문자, 숫자)^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$
공용 파일 마스크^(.+)\\(.+)\.(.+)
주요 신용 카드\d{4}-?\d{4}-?\d{4}-?\d{4}

정규식의 개념

  • 정규식은 복잡한 패턴매칭과 대치 규칙을 정의하는 문자열이다.
  • 정규식은 파일이나 문자열 내에 포함되어 있는 특별한 패턴(또는 특별한 조건을 만족하는 문자열)을 검색하기 위해 미리 정의된 다양한 특수 문자들의 조합이다.
  • 정규식은 니모닉(mnemonic)값으로 간략하게 표현되는 기호로 만들어진다. 예를 들면, 단일 문자열 .은 "임의의 단일 문자열과 매치된다."는 의미이고, 문자 +는 "하나또는 그이상의 앞선식"이라는 의미이다.

    정규식을 정확히 정의하려면, automata, regular language, finite state machine 등을 설명해야 합니다. 그냥 일반적으로는 패턴매칭을 위한 언어라고 넘어갈 수 있지만, 정규식으로 matching할 수 없는 패턴도 많고, 왜 정규식에 이런 연산자가 없을까 고민하기 시작하면, 모든 것이 모호해져버립니다.

    ^ (caret) 라인의 처음이나 문자열의 처음을 표시 ^aaa (문자열의 처음에 aaa를 포함하면 참, 그렇지 않으면 거짓)
    $ (dollar) 라인의 끝이나 문자열의 끝을 표시 aaa$ (문자열의 끝에 aaa를 포함하면 참, 그렇지 않으면 거짓)
    . (period) 임의의 한 문자를 표시 ^a.c (문자열의 처음에 abc, adc, aZc 등은 참, aa 는 거짓)
    a..b$ (문자열의 끝에 aaab, abbb, azzb 등을 포함하면 참)
    [] (bracket) 문자의 집합이나 범위를 나타냄, 두 문자 사이의 "-"는 범위를 나타냄 [] 내에서 "^"이 선행되면 not을 나타냄
    {} (brace) {} 내의 숫자는 직전의 선행문자가 나타나는 횟수 또는 범위를 나타냄 a{3} ('a'의 3번 반복인 aaa만 해당됨)
    * (asterisk) "*" 직전의 선행문자가 0번 또는 여러번 나타나는 문자열 ab*c ('b'를 0번 또는 여러번 포함하므로 ac, ackdddd, abc, abbc, abbbbbbbc 등)
    + "+" 직전의 선행문자가 1번 이상 나타나는 문자열 ab+c ('b'를 1번 또는 여러번 포함하므로 abc, abckdddd, abbc, abbbbbbbc 등, ac는 안됨)
    ? "?" 직전의 선행문자가 0번 또는 1번 나타나는 문자열 ab?c ('b'를 0번 또는 1번 포함하므로 abc, abcd 만 해당됨)
    () (parenthesis) ()는 정규식내에서 패턴을 그룹화 할 때 사용
    | (bar) or를 나타냄 a|b|c (a, b, c 중 하나, 즉 [a-c] 와 동일함)
    \ (backslash) 위에서 사용된 특수 문자들을 정규식내에서 문자로 취급하고 싶을 때 '\'를 선행시켜서 사용하면됨 filename\.ext ("filename.ext"를 나타냄)

    정규식에서는 위에서 언급한 특수 문자를 제외한 나머지 문자들은 일반 문자로 취급함

    위의 정규식 연산자 가운데 vi에서는 지원하지 않는 연산자가 있습니다. vi의 경우 +연산자도 없습니다. regular expression library에 따라 지원하는 연산자의 종류가 상당히 다릅니다. 요즘은 perl-style regular expression이 표준으로 자리잡아가는 것이 대체적인 추세이고, perl의 regular expression은 가장 복합하고 기능이 많은 편입니다.


    [abc](a, b, c 중 어떤 문자, "[a-c]."과 동일)
    [Yy](Y 또는 y)
    [A-Za-z0-9](모든 알파벳과 숫자)
    [-A-Z].("-"(hyphen)과 모든 대문자)
    [^a-z](소문자 이외의 문자)
    [^0-9](숫자 이외의 문자)
    [[:digit:]]([0-9]와 동일)
    a{3,}('a'가 3번 이상 반복인 aaa, aaaa, aaaa, ... 등을 나타냄)
    a{3,5}(aaa, aaaa, aaaaa 만 해당됨)
    ab{2,3}(abb와 abbb 만 해당됨)
    [0-9]{2} (두 자리 숫자)
    doc[7-9]{2}(doc77, doc87, doc97 등이 해당)
    [^Zz]{5}(Z와 z를 포함하지 않는 5개의 문자열, abcde, ttttt 등이 해당)
    .{3,4}er('er'앞에 세 개 또는 네 개의 문자를 포함하는 문자열이므로 Peter, mother 등이 해당)
    * (선행문자가 없는 경우이므로 임의의 문자열 및 공백 문자열도 해당됨)
    .* (선행문자가 "."이므로 하나 이상의 문자를 포함하는 문자열, 공백 문자열은 안됨)
    ab*('b'를 0번 또는 여러번 포함하므로 a, accc, abb, abbbbbbb 등)
    a*('a'를 0번 또는 여러번 포함하므로 k, kdd, sdfrrt, a, aaaa, abb, 공백문자열 등)
    doc[7-9]* (doc7, doc777, doc778989, doc 등이 해당)
    [A-Z].*(대문자로만 이루어진 문자열)
    like.*(직전의 선행문자가 '.'이므로 like에 0 또는 하나 이상의 문자가 추가된 문자열이 됨, like, likely, liker, likelihood 등)
    ab+('b'를 1번 또는 여러번 포함하므로 ab, abccc, abb, abbbbbbb 등)
    like.+(직전의 선행문자가 '.'이므로 like에 하나 이상의 문자가 추가된 문자열이 됨, likely, liker, likelihood 등, 그러나 like는 해당안됨)
    [A-Z]+(대문자로만 이루어진 문자열)
    yes|Yes(yes나 Yes 중 하나, [yY]es와 동일함)
    korea|japan|chinese(korea, japan, chinese 중 하나)
    [\?\[\\\]]('?', '[', '\', ']' 중 하나)

    한글이름 정규식 : [\uac00-\ud7a3]{2,4}

  • 크리에이티브 커먼즈 라이센스
    Creative Commons License

    Posted by 장현준

    2007/02/05 16:10 2007/02/05 16:10
    ,
    Response
    No Trackback , 2 Comments
    RSS :
    http://b4you.net/blog/rss/response/68

    Visual Basic 6.0 에서의 Regular Expression

    1. 메뉴의 프로젝트(P) - 참조(N) 에서 Microsoft VBScript Regular Expressions 5.5 를 체크한다

    2. 다음과 같은 코드를 입력한다.

    Function TestRegExp(myPattern As String, myString As String)
    
    'Create objects.
    Dim objRegExp As RegExp
    Dim objMatch As Match
    Dim colMatches As MatchCollection
    Dim RetStr As String
    
    ' Create a regular expression object.
    Set objRegExp = New RegExp
    
    'Set the pattern by using the Pattern property.
    objRegExp.Pattern = myPattern
    
    ' Set Case Insensitivity.
    objRegExp.IgnoreCase = True
    
    'Set global applicability.
    objRegExp.Global = True
    
    'Test whether the String can be compared.
    If (objRegExp.Test(myString) = True) Then
    
        'Get the matches.
        Set colMatches = objRegExp.Execute(myString)
    
        For Each objMatch In colMatches ' Iterate Matches collection.
    
            RetStr = RetStr & objMatch.FirstIndex & ". Match Value is '"
            RetStr = RetStr & objMatch.Value & "'." & vbCrLf
    
        Next
    
    End If
    
    TestRegExp = RetStr
    
    End Function


    3. 이용한다
    Debug.Print TestRegExp("haha*", "ha1hahasss")



    참고로 정규식은 다음과 같다
    Character Description

    \

    Marks the next character as a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(".

    ^

    Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.

    $

    Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.

    *

    Matches the preceding character or subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}.

    +

    Matches the preceding character or subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.

    ?

    Matches the preceding character or subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}

    {n}

    n is a nonnegative integer. Matches exactly n times. For example, 'o{2}' does not match the 'o' in "Bob," but matches the two o's in "food".

    {n,}

    n is a nonnegative integer. Matches at least n times. For example, 'o{2,}' does not match the "o" in "Bob" and matches all the o's in "foooood". 'o{1,}' is equivalent to 'o+'. 'o{0,}' is equivalent to 'o*'.

    {n,m}

    m and n are nonnegative integers, where n <= m. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood". 'o{0,1}' is equivalent to 'o?'. Note that you cannot put a space between the comma and the numbers.

    ?

    When this character immediately follows any of the other quantifiers (*, +, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. A non-greedy pattern matches as little of the searched string as possible, whereas the default greedy pattern matches as much of the searched string as possible. For example, in the string "oooo", 'o+?' matches a single "o", while 'o+' matches all 'o's.

    .

    Matches any single character except "\n". To match any character including the '\n', use a pattern such as '[\s\S].

    (pattern)

    Matches pattern and captures the match. The captured match can be retrieved from the resulting Matches collection, using the SubMatches collection in VBScript or the $0$9 properties in JScript. To match parentheses characters ( ), use '\(' or '\)'.

    (?:pattern)

    Matches pattern but does not capture the match, that is, it is a non-capturing match that is not stored for possible later use. This is useful for combining parts of a pattern with the "or" character (|). For example, 'industr(?:y|ies) is a more economical expression than 'industry|industries'.

    (?=pattern)

    Positive lookahead matches the search string at any point where a string matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.

    (?!pattern)

    Negative lookahead matches the search string at any point where a string not matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?!95|98|NT|2000)' matches "Windows" in "Windows 3.1" but does not match "Windows" in "Windows 2000". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.

    x|y

    Matches either x or y. For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".

    [xyz]

    A character set. Matches any one of the enclosed characters. For example, '[abc]' matches the 'a' in "plain".

    [^xyz]

    A negative character set. Matches any character not enclosed. For example, '[^abc]' matches the 'p' in "plain".

    [a-z]

    A range of characters. Matches any character in the specified range. For example, '[a-z]' matches any lowercase alphabetic character in the range 'a' through 'z'.

    [^a-z]

    A negative range characters. Matches any character not in the specified range. For example, '[^a-z]' matches any character not in the range 'a' through 'z'.

    \b

    Matches a word boundary, that is, the position between a word and a space. For example, 'er\b' matches the 'er' in "never" but not the 'er' in "verb".

    \B

    Matches a nonword boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never".

    \cx

    Matches the control character indicated by x. For example, \cM matches a Control-M or carriage return character. The value of x must be in the range of A-Z or a-z. If not, c is assumed to be a literal 'c' character.

    \d

    Matches a digit character. Equivalent to [0-9].

    \D

    Matches a nondigit character. Equivalent to [^0-9].

    \f

    Matches a form-feed character. Equivalent to \x0c and \cL.

    \n

    Matches a newline character. Equivalent to \x0a and \cJ.

    \r

    Matches a carriage return character. Equivalent to \x0d and \cM.

    \s

    Matches any white space character including space, tab, form-feed, and so on. Equivalent to [ \f\n\r\t\v].

    \S

    Matches any non-white space character. Equivalent to [^ \f\n\r\t\v].

    \t

    Matches a tab character. Equivalent to \x09 and \cI.

    \v

    Matches a vertical tab character. Equivalent to \x0b and \cK.

    \w

    Matches any word character including underscore. Equivalent to '[A-Za-z0-9_]'.

    \W

    Matches any nonword character. Equivalent to '[^A-Za-z0-9_]'.

    \xn

    Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, '\x41' matches "A". '\x041' is equivalent to '\x04' & "1". Allows ASCII codes to be used in regular expressions.

    \num

    Matches num, where num is a positive integer. A reference back to captured matches. For example, '(.)\1' matches two consecutive identical characters.

    \n

    Identifies either an octal escape value or a backreference. If \n is preceded by at least n captured subexpressions, n is a backreference. Otherwise, n is an octal escape value if n is an octal digit (0-7).

    \nm

    Identifies either an octal escape value or a backreference. If \nm is preceded by at least nm captured subexpressions, nm is a backreference. If \nm is preceded by at least n captures, n is a backreference followed by literal m. If neither of the preceding conditions exist, \nm matches octal escape value nm when n and m are octal digits (0-7).

    \nml

    Matches octal escape value nml when n is an octal digit (0-3) and m and l are octal digits (0-7).

    \un

    Matches n, where n is a Unicode character expressed as four hexadecimal digits. For example, \u00A9 matches the copyright symbol (?).

    크리에이티브 커먼즈 라이센스
    Creative Commons License

    Posted by 장현준

    2007/01/28 01:41 2007/01/28 01:41
    , ,
    Response
    No Trackback , No Comment
    RSS :
    http://b4you.net/blog/rss/response/59


    블로그 이미지

    빗소리를 먹는 사람.

    - 장현준

    Notices

    Archives

    Authors

    1. 장현준

    Recent Trackbacks

    1. 듀얼클러치의 생각 rsvin28's me2DAY 2009

    Calendar

    «   2012/02   »
          1 2 3 4
    5 6 7 8 9 10 11
    12 13 14 15 16 17 18
    19 20 21 22 23 24 25
    26 27 28 29      

    Site Stats

    Total hits:
    158026
    Today:
    96
    Yesterday:
    228