-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexp_metacharacter.rb
76 lines (64 loc) · 2.69 KB
/
regexp_metacharacter.rb
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# frozen_string_literal: true
module RuboCop
module Cop
# Common functionality for handling regexp metacharacters.
module RegexpMetacharacter
private
def literal_at_start?(regexp)
return true if literal_at_start_with_backslash_a?(regexp)
!safe_multiline? && literal_at_start_with_caret?(regexp)
end
def literal_at_end?(regexp)
return true if literal_at_end_with_backslash_z?(regexp)
!safe_multiline? && literal_at_end_with_dollar?(regexp)
end
def literal_at_start_with_backslash_a?(regex_str)
# is this regexp 'literal' in the sense of only matching literal
# chars, rather than using metachars like `.` and `*` and so on?
# also, is it anchored at the start of the string?
# (tricky: \s, \d, and so on are metacharacters, but other characters
# escaped with a slash are just literals. LITERAL_REGEX takes all
# that into account.)
/\A\\A(?:#{Util::LITERAL_REGEX})+\z/o.match?(regex_str)
end
def literal_at_start_with_caret?(regex_str)
# is this regexp 'literal' in the sense of only matching literal
# chars, rather than using metachars like `.` and `*` and so on?
# also, is it anchored at the start of the string?
# (tricky: \s, \d, and so on are metacharacters, but other characters
# escaped with a slash are just literals. LITERAL_REGEX takes all
# that into account.)
/\A\^(?:#{Util::LITERAL_REGEX})+\z/o.match?(regex_str)
end
def literal_at_end_with_backslash_z?(regex_str)
# is this regexp 'literal' in the sense of only matching literal
# chars, rather than using metachars like . and * and so on?
# also, is it anchored at the end of the string?
/\A(?:#{Util::LITERAL_REGEX})+\\z\z/o.match?(regex_str)
end
def literal_at_end_with_dollar?(regex_str)
# is this regexp 'literal' in the sense of only matching literal
# chars, rather than using metachars like . and * and so on?
# also, is it anchored at the end of the string?
/\A(?:#{Util::LITERAL_REGEX})+\$\z/o.match?(regex_str)
end
def drop_start_metacharacter(regexp_string)
if regexp_string.start_with?('\\A')
regexp_string[2..] # drop `\A` anchor
else
regexp_string[1..] # drop `^` anchor
end
end
def drop_end_metacharacter(regexp_string)
if regexp_string.end_with?('\\z')
regexp_string.chomp('\z') # drop `\z` anchor
else
regexp_string.chop # drop `$` anchor
end
end
def safe_multiline?
cop_config.fetch('SafeMultiline', true)
end
end
end
end