-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathunions.rb
executable file
·47 lines (39 loc) · 1.03 KB
/
unions.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
#!/usr/bin/env ruby
# Combining regular expressions with Regexp.union
# Avdi Grimm has covered this in his Ruby Tapas screencast (paid)
# http://www.rubytapas.com/episodes/199-Regexp-Union
head_re = /(?<head><[\/]?head>)/i
body_re = /(?<body><[\/]?body>)/
paragraph_re = /(?<paragraph><[\/]?p>)/
test_text = <<EOP
<head>
<title>This</title>
<meta></meta>
</head>
<body>
<div>Unprinted text.<div>
<p>Some text.</p>
</body>
EOP
re = Regexp.union(
head_re,
body_re,
paragraph_re
)
test_text.each_line do |line|
line.chomp
# The === operator returns true if the string on the
# right matches the regular expression on the left
puts "#{line}" if re === line
end
puts '','The regular expression',re.inspect
puts '','As you can see, it preserves any regex flags you include.'
__END__
<head>
</head>
<body>
<p>Some text.</p>
</body>
The regular expression
/(?i-mx:(?<head><[\/]?head>))|(?-mix:(?<body><[\/]?body>))|(?-mix:(?<paragraph><[\/]?p>))/
As you can see, it preserves any regex flags you include.