티스토리 뷰

dev

정규식 - Repetition Expressions

altvirus 2015. 2. 2. 17:56

□ Repetition metacharacters 



Regex:  /apples*/

String: "apple apples applesssssss"


Regex:  /apples+/

String: "apple apples applesssssss"


Regex:  /apples?/

String: "apple apples applesssssss"



Regex:  /\d\d\d\d*/

String: "123456789 1234 123 12"


Regex:  /\d\d\d+/

String: "123456789 1234 123 12"



Regex:  /[a-z]+\d[a-z]*/

String: "abc9xyz"

String: "a9xyz"

String: "9xyz"


Regex:  /[a-z]+\d[a-z]*/

String: "abc9xyz"

String: "abc9z"

String: "abc9"



Optional letter "u"


Regex:  /colou?r/

String: "color colour"



Find any word that ends in "s"


Regex:  /\w+s/

String: "We picked apples."


□ Quantified repetition


{최소값, 최대값}

- 최소값은 꼭 써야한다.(0도 괜찮음)

- 최대값은 생략가능


Shall I compare thee to a summer's day?

Thou art more lovely and more temperate:

Rough winds do shake the darling buds of May,

And summer's lease hath all too short a date.


Regex:  /\w{5}\s/ => (5글자+공백)

String: (use shakespeare_sonnet.txt)


Regex:  /\w{2,5}\s/

Regex:  /\w{5,}\s/



Regex:  /\d{3}-\d{3}-\d{4}/

String: 555-867-5309


Regex:  /A{1,2} bonds/

String: "A bonds AA bonds AAA bonds"



Regex:  /\w+_\d+-\d+/

String: "report_1997-04 budget_03-04 memo_712539-100"


Regex:  /\w+_\d{2,4}-\d{2}/

String: "report_1997-04 budget_03-04 memo_712539-100"


□ Greedy expressions


Regex:  /.+\.jpg/

String: "filename.jpg"


Regex:  /.*[0-9]+/

String: "Page 266"


Regex:  /\d+\w+\d+/

String: "01_FY_07_report_99.xls"


Regex:  /".+", ".+"/

String: "Milton", "Waddams", "Initech, Inc."


□ Lazy expressions

Remove the ? from each regex and watch the changes.


Regex:  /\w*?\d{3}/

String: "image_294"


Regex:  /[A-Za-z-.]+?\./

String: "Dr. Roberts, M.D."


Regex:  /.{4,8}_.{2,6}?/

String: "last_qtr_report.xls"


Regex:  /apples??/

String: "We picked apples."


□ Using repetition efficiently


Regex:  /\w*s/

String: "We picked apples."


Regex:  /\w+s/

String: "We picked apples."


Regex:  /[A-Za-z]+s/

String: "We picked apples."


Regex:  /\s[A-Za-z]+s/

String: "We picked apples."


Regex:  /\s[a-z]+s/

String: "We picked apples."


Regex:  /\s[a-z]{5}s/

String: "We picked apples."



'dev' 카테고리의 다른 글

리소스  (1) 2015.04.21
파이썬 관련 강좌 올리는 님. django 등  (0) 2015.02.14
이클립스 moonrise 테마  (0) 2015.02.14
정규식 - Character Sets  (0) 2015.01.30
정규식 - Characters  (0) 2015.01.30
공지사항