Koan - Regular Expressions
Case 83
정규표현식의 클래스는 Regexp이다.
def test_a_pattern_is_a_regular_expression
assert_equal __, /pattern/.class
end
Case 84
/x?/
는 존재하거나 존재하지 않는다는 의미이다. 테스트케이스의 의미처럼 option이라고 생각하자. 그리고 정규표현식의 기호는 다음을 참고하자. (http://www.nextree.co.kr/wp-content/uploads/2014/01/jhkim-140117-RegularExpression-06.png)
def test_question_mark_means_optional
assert_equal __, "abbcccddddeeeee"[/ab?/]
assert_equal __, "abbcccddddeeeee"[/az?/]
end
Case 88
/x*/
는 x가 0번이상 반복하는 것을 의미한다. 3번째 테스트케이스는 nil이 아니다. (0번이상에 주의하자)
def test_asterisk_means_zero_or_more
assert_equal __, "abbcccddddeeeee"[/ab*/]
assert_equal __, "abbcccddddeeeee"[/az*/]
assert_equal __, "abbcccddddeeeee"[/z*/]
end
Case 90
ruby에서 문자열[ ]
는 문자열에서 정규표현식을 조사하는 구문이고, select
는 조건을 만족하는 원소를 추출하는 메소드이다.
def test_character_classes_give_options_for_a_character
animals = ["cat", "bat", "rat", "zat"]
assert_equal __, animals.select { |a| a[/[cbr]at/] }
end
Case 93
공백문자 처리시에 \t\n
도 포함된다.
def test_slash_s_is_a_shortcut_for_a_whitespace_character_class
assert_equal __, "space: \t\n"[/\s+/]
end
Case 96
[/[^0-9]+/]
는 not 으로 사용되었다.
def test_a_character_class_can_be_negated
assert_equal "the number is ", "the number is 42"[/[^0-9]+/]
end
Case 97
def test_shortcut_character_classes_are_negated_with_capitals
assert_equal __, "the number is 42"[/\D+/]
assert_equal __, "space: \t\n"[/\S+/]
assert_equal __, "variable_1 = 42"[/[^a-zA-Z0-9_]+/]
assert_equal __, "variable_1 = 42"[/\W+/]
end
Case 98
def test_slash_a_anchors_to_the_start_of_the_string
assert_equal __, "start end"[/\Astart/]
assert_equal __, "start end"[/\Aend/]
end