1 |
argrath |
1.1 |
|
2 |
|
|
=encoding euc-jp |
3 |
|
|
|
4 |
|
|
=head1 NAME |
5 |
|
|
|
6 |
|
|
=begin original |
7 |
|
|
|
8 |
|
|
perlfaq6 - Regular Expressions |
9 |
|
|
|
10 |
|
|
=end original |
11 |
|
|
|
12 |
|
|
perlfaq6 - 正規表現 |
13 |
|
|
|
14 |
|
|
=head1 DESCRIPTION |
15 |
|
|
|
16 |
|
|
=begin original |
17 |
|
|
|
18 |
|
|
This section is surprisingly small because the rest of the FAQ is |
19 |
|
|
littered with answers involving regular expressions. For example, |
20 |
|
|
decoding a URL and checking whether something is a number can be handled |
21 |
|
|
with regular expressions, but those answers are found elsewhere in |
22 |
|
|
this document (in L<perlfaq9>: "How do I decode or create those %-encodings |
23 |
|
|
on the web" and L<perlfaq4>: "How do I determine whether a scalar is |
24 |
|
|
a number/whole/integer/float", to be precise). |
25 |
|
|
|
26 |
|
|
=end original |
27 |
|
|
|
28 |
|
|
この章は驚くほど小さくなっています。 |
29 |
|
|
なぜなら FAQ の残りの部分は正規表現を伴った回答と一緒にあちこちに |
30 |
|
|
散在しているからです。 |
31 |
|
|
たとえば URL をデコードするとかあるものが数値かどうか確認することは |
32 |
|
|
正規表現を使って処理されますが、この回答はこの資料のあらゆる所で |
33 |
|
|
見つけることができます(正確には L<perlfaq9>: |
34 |
|
|
"How do I decode or create those %-encodings on the web" と |
35 |
|
|
L<perlfaq4>: "How do I determine whether a scalar is |
36 |
|
|
a number/whole/integer/float")。 |
37 |
|
|
|
38 |
|
|
=head2 How can I hope to use regular expressions without creating illegible and unmaintainable code? |
39 |
|
|
X<regex, legibility> X<regexp, legibility> |
40 |
|
|
X<regular expression, legibility> X</x> |
41 |
|
|
|
42 |
|
|
(判読し難い、保守できないようなものにすることなく正規表現を使うには?) |
43 |
|
|
|
44 |
|
|
=begin original |
45 |
|
|
|
46 |
|
|
Three techniques can make regular expressions maintainable and |
47 |
|
|
understandable. |
48 |
|
|
|
49 |
|
|
=end original |
50 |
|
|
|
51 |
|
|
正規表現を保守可能なものにし、理解できるようにするための |
52 |
|
|
三つの技法があります。 |
53 |
|
|
|
54 |
|
|
=over 4 |
55 |
|
|
|
56 |
|
|
=item Comments Outside the Regex |
57 |
|
|
|
58 |
|
|
(正規表現の外側にコメントを付ける) |
59 |
|
|
|
60 |
|
|
=begin original |
61 |
|
|
|
62 |
|
|
Describe what you're doing and how you're doing it, using normal Perl |
63 |
|
|
comments. |
64 |
|
|
|
65 |
|
|
=end original |
66 |
|
|
|
67 |
|
|
通常のPerlのコメントを使って、 |
68 |
|
|
あなたが何を、どのようにしているかを説明します。 |
69 |
|
|
|
70 |
|
|
# turn the line into the first word, a colon, and the |
71 |
|
|
# number of characters on the rest of the line |
72 |
|
|
s/^(\w+)(.*)/ lc($1) . ":" . length($2) /meg; |
73 |
|
|
|
74 |
|
|
=item Comments Inside the Regex |
75 |
|
|
|
76 |
|
|
(正規表現の内側にコメントを付ける) |
77 |
|
|
|
78 |
|
|
=begin original |
79 |
|
|
|
80 |
|
|
The C</x> modifier causes whitespace to be ignored in a regex pattern |
81 |
|
|
(except in a character class and a few other places), and also allows you to |
82 |
|
|
use normal comments there, too. As you can imagine, whitespace and comments |
83 |
|
|
help a lot. |
84 |
|
|
|
85 |
|
|
=end original |
86 |
|
|
|
87 |
|
|
<CODE>/x</CODE> 修飾子は、正規表現中にある空白を無視するようにし、 |
88 |
|
|
(文字クラスの中とその他いくつかにあるものを除く)、通常のコメントが使えるように |
89 |
|
|
します。 |
90 |
|
|
あなたの想像できるように、空白とコメントは非常に助けに |
91 |
|
|
なります。 |
92 |
|
|
|
93 |
|
|
=begin original |
94 |
|
|
|
95 |
|
|
C</x> lets you turn this: |
96 |
|
|
|
97 |
|
|
=end original |
98 |
|
|
|
99 |
|
|
C</x>によって |
100 |
|
|
|
101 |
|
|
s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs; |
102 |
|
|
|
103 |
|
|
=begin original |
104 |
|
|
|
105 |
|
|
into this: |
106 |
|
|
|
107 |
|
|
=end original |
108 |
|
|
|
109 |
|
|
この正規表現を以下の様に記述できます: |
110 |
|
|
|
111 |
|
|
s{ < # opening angle bracket |
112 |
|
|
(?: # Non-backreffing grouping paren |
113 |
|
|
[^>'"] * # 0 or more things that are neither > nor ' nor " |
114 |
|
|
| # or else |
115 |
|
|
".*?" # a section between double quotes (stingy match) |
116 |
|
|
| # or else |
117 |
|
|
'.*?' # a section between single quotes (stingy match) |
118 |
|
|
) + # all occurring one or more times |
119 |
|
|
> # closing angle bracket |
120 |
|
|
}{}gsx; # replace with nothing, i.e. delete |
121 |
|
|
|
122 |
|
|
=begin original |
123 |
|
|
|
124 |
|
|
It's still not quite so clear as prose, but it is very useful for |
125 |
|
|
describing the meaning of each part of the pattern. |
126 |
|
|
|
127 |
|
|
=end original |
128 |
|
|
|
129 |
|
|
これでもまだ散文(prose)程には明確にはなっていませんが、 |
130 |
|
|
パターンの各部分の意味を説明するには非常に便利なものです。 |
131 |
|
|
|
132 |
|
|
=item Different Delimiters |
133 |
|
|
|
134 |
|
|
(異なった区切り) |
135 |
|
|
|
136 |
|
|
=begin original |
137 |
|
|
|
138 |
|
|
While we normally think of patterns as being delimited with C</> |
139 |
|
|
characters, they can be delimited by almost any character. L<perlre> |
140 |
|
|
describes this. For example, the C<s///> above uses braces as |
141 |
|
|
delimiters. Selecting another delimiter can avoid quoting the |
142 |
|
|
delimiter within the pattern: |
143 |
|
|
|
144 |
|
|
=end original |
145 |
|
|
|
146 |
|
|
私たちは通常、C</>で区切られたものをパターンであると考えていますが、 |
147 |
|
|
パターンはほとんどすべてのキャラクタを使って区切ることが可能です。 |
148 |
|
|
L<perlre>はこれを説明しています。 |
149 |
|
|
たとえば、先に挙げたC<s///> |
150 |
|
|
では、区切りとしてカーリーブレースを使っています。 |
151 |
|
|
スラッシュ以外の区切りを選択することによって、パターンの中に存在する |
152 |
|
|
区切り記号と同じものをクォートする手間を省くことができます。 |
153 |
|
|
|
154 |
|
|
s/\/usr\/local/\/usr\/share/g; # bad delimiter choice |
155 |
|
|
s#/usr/local#/usr/share#g; # better |
156 |
|
|
|
157 |
|
|
=begin original |
158 |
|
|
|
159 |
|
|
Using logically paired delimiters can be even more readable: |
160 |
|
|
|
161 |
|
|
=end original |
162 |
|
|
|
163 |
|
|
Using logically paired delimiters can be even more readable: |
164 |
|
|
(TBT) |
165 |
|
|
|
166 |
|
|
s{/usr/local/}{/usr/share}g; # better still |
167 |
|
|
|
168 |
|
|
=back |
169 |
|
|
|
170 |
|
|
=head2 I'm having trouble matching over more than one line. What's wrong? |
171 |
|
|
X<regex, multiline> X<regexp, multiline> X<regular expression, multiline> |
172 |
|
|
|
173 |
|
|
(二行以上に対するマッチングでトラブルがありました。何が悪いのでしょう?) |
174 |
|
|
|
175 |
|
|
=begin original |
176 |
|
|
|
177 |
|
|
Either you don't have more than one line in the string you're looking |
178 |
|
|
at (probably), or else you aren't using the correct modifier(s) on |
179 |
|
|
your pattern (possibly). |
180 |
|
|
|
181 |
|
|
=end original |
182 |
|
|
|
183 |
|
|
マッチングの対象となっている文字列が実際には二行以上になっていないか、 |
184 |
|
|
パターンで正しい修飾子 (modifier)を使っていないかのいずれかでしょう |
185 |
|
|
(多分)。 |
186 |
|
|
|
187 |
|
|
=begin original |
188 |
|
|
|
189 |
|
|
There are many ways to get multiline data into a string. If you want |
190 |
|
|
it to happen automatically while reading input, you'll want to set $/ |
191 |
|
|
(probably to '' for paragraphs or C<undef> for the whole file) to |
192 |
|
|
allow you to read more than one line at a time. |
193 |
|
|
|
194 |
|
|
=end original |
195 |
|
|
|
196 |
|
|
複数行のデータを一つの文字列にする方法はたくさんあります。 |
197 |
|
|
これを、入力を読み込んでいる間自動で行なわせたいというのであれば、 |
198 |
|
|
一度に二行以上読ませるために $/を(パラグラフ単位で読み込みたいなら '' を、 |
199 |
|
|
ファイル全体を読み込みたいなら C<undef> を)設定したくなるでしょう。 |
200 |
|
|
|
201 |
|
|
=begin original |
202 |
|
|
|
203 |
|
|
Read L<perlre> to help you decide which of C</s> and C</m> (or both) |
204 |
|
|
you might want to use: C</s> allows dot to include newline, and C</m> |
205 |
|
|
allows caret and dollar to match next to a newline, not just at the |
206 |
|
|
end of the string. You do need to make sure that you've actually |
207 |
|
|
got a multiline string in there. |
208 |
|
|
|
209 |
|
|
=end original |
210 |
|
|
|
211 |
|
|
あなたが使いたいのは C</s> か C</m> のいずれなのか(あるいはこれら |
212 |
|
|
両方なのか)を決めるのを助けるために、L<perlre> を読んでください: |
213 |
|
|
C</s> はドットが改行を含むようにしますし、C</m> はキャレットとドル記号が |
214 |
|
|
文字列の両端だけでなく改行の前後でマッチするようにします。 |
215 |
|
|
そして、複数行に渡る文字列を取得するようにさせる必要があります。 |
216 |
|
|
|
217 |
|
|
=begin original |
218 |
|
|
|
219 |
|
|
For example, this program detects duplicate words, even when they span |
220 |
|
|
line breaks (but not paragraph ones). For this example, we don't need |
221 |
|
|
C</s> because we aren't using dot in a regular expression that we want |
222 |
|
|
to cross line boundaries. Neither do we need C</m> because we don't |
223 |
|
|
want caret or dollar to match at any point inside the record next |
224 |
|
|
to newlines. But it's imperative that $/ be set to something other |
225 |
|
|
than the default, or else we won't actually ever have a multiline |
226 |
|
|
record read in. |
227 |
|
|
|
228 |
|
|
=end original |
229 |
|
|
|
230 |
|
|
たとえば、以下に挙げるプログラムは重複した単語を、たとえそれが行を |
231 |
|
|
またがっていても(ただしパラグラフはまたがっていない)探し出すものです。 |
232 |
|
|
この例では、C</s>の必要はありません。 |
233 |
|
|
なぜなら、この行をまたがらせたい正規表現でドットを使っていないからです。 |
234 |
|
|
C</m>を使う必要もありません。 |
235 |
|
|
それは、キャレットやドル記号をレコードの中にある改行の前後で |
236 |
|
|
マッチさせることは望んでいないからです。 |
237 |
|
|
しかし、$/ をデフォルト以外のものに設定することは避けられませんし、 |
238 |
|
|
そうしなければ複数行レコードを読み込むことはできないのです。 |
239 |
|
|
|
240 |
|
|
$/ = ''; # read in whole paragraph, not just one line |
241 |
|
|
while ( <> ) { |
242 |
|
|
while ( /\b([\w'-]+)(\s+\g1)+\b/gi ) { # word starts alpha |
243 |
|
|
print "Duplicate $1 at paragraph $.\n"; |
244 |
|
|
} |
245 |
|
|
} |
246 |
|
|
|
247 |
|
|
=begin original |
248 |
|
|
|
249 |
|
|
Here's some code that finds sentences that begin with "From " (which would |
250 |
|
|
be mangled by many mailers): |
251 |
|
|
|
252 |
|
|
=end original |
253 |
|
|
|
254 |
|
|
以下の例は、“From ”で始まるセンテンス(多くのメイラーによって |
255 |
|
|
変形されるであろうもの)を検索するものです。 |
256 |
|
|
|
257 |
|
|
$/ = ''; # read in whole paragraph, not just one line |
258 |
|
|
while ( <> ) { |
259 |
|
|
while ( /^From /gm ) { # /m makes ^ match next to \n |
260 |
|
|
print "leading from in paragraph $.\n"; |
261 |
|
|
} |
262 |
|
|
} |
263 |
|
|
|
264 |
|
|
=begin original |
265 |
|
|
|
266 |
|
|
Here's code that finds everything between START and END in a paragraph: |
267 |
|
|
|
268 |
|
|
=end original |
269 |
|
|
|
270 |
|
|
次の例は、パラグラフ中の START と END に挟まれた部分を検索するものです: |
271 |
|
|
|
272 |
|
|
undef $/; # read in whole file, not just one line or paragraph |
273 |
|
|
while ( <> ) { |
274 |
|
|
while ( /START(.*?)END/sgm ) { # /s makes . cross line boundaries |
275 |
|
|
print "$1\n"; |
276 |
|
|
} |
277 |
|
|
} |
278 |
|
|
|
279 |
|
|
=head2 How can I pull out lines between two patterns that are themselves on different lines? |
280 |
|
|
X<..> |
281 |
|
|
|
282 |
|
|
(異なる行にある二つのパターンに挟まれている行を取り出すのはどうやればできますか?) |
283 |
|
|
|
284 |
|
|
=begin original |
285 |
|
|
|
286 |
|
|
You can use Perl's somewhat exotic C<..> operator (documented in |
287 |
|
|
L<perlop>): |
288 |
|
|
|
289 |
|
|
=end original |
290 |
|
|
|
291 |
|
|
Perlの C<..> 演算子を使えます(L<perlop> に説明があります)。 |
292 |
|
|
|
293 |
|
|
perl -ne 'print if /START/ .. /END/' file1 file2 ... |
294 |
|
|
|
295 |
|
|
=begin original |
296 |
|
|
|
297 |
|
|
If you wanted text and not lines, you would use |
298 |
|
|
|
299 |
|
|
=end original |
300 |
|
|
|
301 |
|
|
行ではなく、テキストが必要なら次のようにします |
302 |
|
|
|
303 |
|
|
perl -0777 -ne 'print "$1\n" while /START(.*?)END/gs' file1 file2 ... |
304 |
|
|
|
305 |
|
|
=begin original |
306 |
|
|
|
307 |
|
|
But if you want nested occurrences of C<START> through C<END>, you'll |
308 |
|
|
run up against the problem described in the question in this section |
309 |
|
|
on matching balanced text. |
310 |
|
|
|
311 |
|
|
=end original |
312 |
|
|
|
313 |
|
|
しかし、C<START> と C<END> が現れるのを入れ子にさせたいというのであれば、 |
314 |
|
|
このセクションにある質問で説明されている問題に直面することになります。 |
315 |
|
|
|
316 |
|
|
=begin original |
317 |
|
|
|
318 |
|
|
Here's another example of using C<..>: |
319 |
|
|
|
320 |
|
|
=end original |
321 |
|
|
|
322 |
|
|
C<..>を使った別の例です: |
323 |
|
|
|
324 |
|
|
while (<>) { |
325 |
|
|
my $in_header = 1 .. /^$/; |
326 |
|
|
my $in_body = /^$/ .. eof; |
327 |
|
|
# now choose between them |
328 |
|
|
} continue { |
329 |
|
|
$. = 0 if eof; # fix $. |
330 |
|
|
} |
331 |
|
|
|
332 |
|
|
=head2 How do I match XML, HTML, or other nasty, ugly things with a regex? |
333 |
|
|
X<regex, XML> X<regex, HTML> X<XML> X<HTML> X<pain> X<frustration> |
334 |
|
|
X<sucking out, will to live> |
335 |
|
|
|
336 |
|
|
(XML, HTML あるいはその他の扱いにくくて不細工なものを正規表現でマッチングさせるには?) |
337 |
|
|
|
338 |
|
|
=begin original |
339 |
|
|
|
340 |
|
|
Do not use regexes. Use a module and forget about the |
341 |
|
|
regular expressions. The L<XML::LibXML>, L<HTML::TokeParser> and |
342 |
|
|
L<HTML::TreeBuilder> modules are good starts, although each namespace |
343 |
|
|
has other parsing modules specialized for certain tasks and different |
344 |
|
|
ways of doing it. Start at CPAN Search ( L<http://metacpan.org/> ) |
345 |
|
|
and wonder at all the work people have done for you already! :) |
346 |
|
|
|
347 |
|
|
=end original |
348 |
|
|
|
349 |
|
|
Do not use regexes. Use a module and forget about the |
350 |
|
|
regular expressions. The L<XML::LibXML>, L<HTML::TokeParser> and |
351 |
|
|
L<HTML::TreeBuilder> modules are good starts, although each namespace |
352 |
|
|
has other parsing modules specialized for certain tasks and different |
353 |
|
|
ways of doing it. Start at CPAN Search ( L<http://metacpan.org/> ) |
354 |
|
|
and wonder at all the work people have done for you already! :) |
355 |
|
|
(TBT) |
356 |
|
|
|
357 |
|
|
=head2 I put a regular expression into $/ but it didn't work. What's wrong? |
358 |
|
|
X<$/, regexes in> X<$INPUT_RECORD_SEPARATOR, regexes in> |
359 |
|
|
X<$RS, regexes in> |
360 |
|
|
|
361 |
|
|
($/ に正規表現を入れたけど動きません。何が悪いの?) |
362 |
|
|
|
363 |
|
|
=begin original |
364 |
|
|
|
365 |
|
|
$/ has to be a string. You can use these examples if you really need to |
366 |
|
|
do this. |
367 |
|
|
|
368 |
|
|
=end original |
369 |
|
|
|
370 |
|
|
$/ は文字列でなければなりません。 |
371 |
|
|
もし本当にそうする必要があるなら、以下の例が使えます。 |
372 |
|
|
|
373 |
|
|
=begin original |
374 |
|
|
|
375 |
|
|
If you have L<File::Stream>, this is easy. |
376 |
|
|
|
377 |
|
|
=end original |
378 |
|
|
|
379 |
|
|
もし L<File::Stream> があれば、簡単です。 |
380 |
|
|
|
381 |
|
|
use File::Stream; |
382 |
|
|
|
383 |
|
|
my $stream = File::Stream->new( |
384 |
|
|
$filehandle, |
385 |
|
|
separator => qr/\s*,\s*/, |
386 |
|
|
); |
387 |
|
|
|
388 |
|
|
print "$_\n" while <$stream>; |
389 |
|
|
|
390 |
|
|
=begin original |
391 |
|
|
|
392 |
|
|
If you don't have File::Stream, you have to do a little more work. |
393 |
|
|
|
394 |
|
|
=end original |
395 |
|
|
|
396 |
|
|
File::Stream がなければ、もう少し作業が必要です。 |
397 |
|
|
|
398 |
|
|
=begin original |
399 |
|
|
|
400 |
|
|
You can use the four-argument form of sysread to continually add to |
401 |
|
|
a buffer. After you add to the buffer, you check if you have a |
402 |
|
|
complete line (using your regular expression). |
403 |
|
|
|
404 |
|
|
=end original |
405 |
|
|
|
406 |
|
|
継続的にバッファに追加するために、sysread の 4 引数形式が使えます。 |
407 |
|
|
バッファに追加した後、(正規表現を使って)行全体が揃っているかを |
408 |
|
|
チェックします。 |
409 |
|
|
|
410 |
|
|
local $_ = ""; |
411 |
|
|
while( sysread FH, $_, 8192, length ) { |
412 |
|
|
while( s/^((?s).*?)your_pattern// ) { |
413 |
|
|
my $record = $1; |
414 |
|
|
# do stuff here. |
415 |
|
|
} |
416 |
|
|
} |
417 |
|
|
|
418 |
|
|
=begin original |
419 |
|
|
|
420 |
|
|
You can do the same thing with foreach and a match using the |
421 |
|
|
c flag and the \G anchor, if you do not mind your entire file |
422 |
|
|
being in memory at the end. |
423 |
|
|
|
424 |
|
|
=end original |
425 |
|
|
|
426 |
|
|
もしファイル全体を最後までメモリに入れることを気にしないのなら、 |
427 |
|
|
foreach および、c フラグと \G アンカーを使ったマッチングを使って |
428 |
|
|
同じことができます。 |
429 |
|
|
|
430 |
|
|
local $_ = ""; |
431 |
|
|
while( sysread FH, $_, 8192, length ) { |
432 |
|
|
foreach my $record ( m/\G((?s).*?)your_pattern/gc ) { |
433 |
|
|
# do stuff here. |
434 |
|
|
} |
435 |
|
|
substr( $_, 0, pos ) = "" if pos; |
436 |
|
|
} |
437 |
|
|
|
438 |
|
|
=head2 How do I substitute case-insensitively on the LHS while preserving case on the RHS? |
439 |
|
|
X<replace, case preserving> X<substitute, case preserving> |
440 |
|
|
X<substitution, case preserving> X<s, case preserving> |
441 |
|
|
|
442 |
|
|
(演算子の左辺では大小文字を無視して、演算子の右辺では元の大小文字を保存しておくような置換をするには?) |
443 |
|
|
|
444 |
|
|
=begin original |
445 |
|
|
|
446 |
|
|
Here's a lovely Perlish solution by Larry Rosler. It exploits |
447 |
|
|
properties of bitwise xor on ASCII strings. |
448 |
|
|
|
449 |
|
|
=end original |
450 |
|
|
|
451 |
|
|
以下に Larry Rosler によるとっても Perl ぽい解法があります。 |
452 |
|
|
これは ASCII 文字列に対するビット xor の動作を悪用します。 |
453 |
|
|
|
454 |
|
|
$_= "this is a TEsT case"; |
455 |
|
|
|
456 |
|
|
$old = 'test'; |
457 |
|
|
$new = 'success'; |
458 |
|
|
|
459 |
|
|
s{(\Q$old\E)} |
460 |
|
|
{ uc $new | (uc $1 ^ $1) . |
461 |
|
|
(uc(substr $1, -1) ^ substr $1, -1) x |
462 |
|
|
(length($new) - length $1) |
463 |
|
|
}egi; |
464 |
|
|
|
465 |
|
|
print; |
466 |
|
|
|
467 |
|
|
=begin original |
468 |
|
|
|
469 |
|
|
And here it is as a subroutine, modeled after the above: |
470 |
|
|
|
471 |
|
|
=end original |
472 |
|
|
|
473 |
|
|
以下はサブルーチンにしたものです。 |
474 |
|
|
上記と同じ手法です: |
475 |
|
|
|
476 |
|
|
sub preserve_case($$) { |
477 |
|
|
my ($old, $new) = @_; |
478 |
|
|
my $mask = uc $old ^ $old; |
479 |
|
|
|
480 |
|
|
uc $new | $mask . |
481 |
|
|
substr($mask, -1) x (length($new) - length($old)) |
482 |
|
|
} |
483 |
|
|
|
484 |
|
|
$string = "this is a TEsT case"; |
485 |
|
|
$string =~ s/(test)/preserve_case($1, "success")/egi; |
486 |
|
|
print "$string\n"; |
487 |
|
|
|
488 |
|
|
=begin original |
489 |
|
|
|
490 |
|
|
This prints: |
491 |
|
|
|
492 |
|
|
=end original |
493 |
|
|
|
494 |
|
|
これは以下のように表示します: |
495 |
|
|
|
496 |
|
|
this is a SUcCESS case |
497 |
|
|
|
498 |
|
|
=begin original |
499 |
|
|
|
500 |
|
|
As an alternative, to keep the case of the replacement word if it is |
501 |
|
|
longer than the original, you can use this code, by Jeff Pinyan: |
502 |
|
|
|
503 |
|
|
=end original |
504 |
|
|
|
505 |
|
|
代替案として、もし元のものの方が長い場合には置き換え単語の大文字小文字を |
506 |
|
|
維持する場合は、Jeff Pinyan による以下のコードが使えます: |
507 |
|
|
|
508 |
|
|
sub preserve_case { |
509 |
|
|
my ($from, $to) = @_; |
510 |
|
|
my ($lf, $lt) = map length, @_; |
511 |
|
|
|
512 |
|
|
if ($lt < $lf) { $from = substr $from, 0, $lt } |
513 |
|
|
else { $from .= substr $to, $lf } |
514 |
|
|
|
515 |
|
|
return uc $to | ($from ^ uc $from); |
516 |
|
|
} |
517 |
|
|
|
518 |
|
|
=begin original |
519 |
|
|
|
520 |
|
|
This changes the sentence to "this is a SUcCess case." |
521 |
|
|
|
522 |
|
|
=end original |
523 |
|
|
|
524 |
|
|
これは文章を "this is a SUcCess case." に変更します。 |
525 |
|
|
|
526 |
|
|
=begin original |
527 |
|
|
|
528 |
|
|
Just to show that C programmers can write C in any programming language, |
529 |
|
|
if you prefer a more C-like solution, the following script makes the |
530 |
|
|
substitution have the same case, letter by letter, as the original. |
531 |
|
|
(It also happens to run about 240% slower than the Perlish solution runs.) |
532 |
|
|
If the substitution has more characters than the string being substituted, |
533 |
|
|
the case of the last character is used for the rest of the substitution. |
534 |
|
|
|
535 |
|
|
=end original |
536 |
|
|
|
537 |
|
|
もしもっと C っぽい解決法が好みなら、 |
538 |
|
|
以下に挙げるスクリプトは、大小文字の違いを保ったまま、 |
539 |
|
|
文字毎に置換を行ないます。 |
540 |
|
|
(そしてこれは Perl っぽい解法より 240% 遅いです。) |
541 |
|
|
置換対象の文字列よりも多くの文字が置換後の文字列にあるのであれば、 |
542 |
|
|
最後の文字の大小文字の種別が置換後の文字列の残りの部分の |
543 |
|
|
文字に対して使われます。 |
544 |
|
|
|
545 |
|
|
# Original by Nathan Torkington, massaged by Jeffrey Friedl |
546 |
|
|
# |
547 |
|
|
sub preserve_case($$) |
548 |
|
|
{ |
549 |
|
|
my ($old, $new) = @_; |
550 |
|
|
my $state = 0; # 0 = no change; 1 = lc; 2 = uc |
551 |
|
|
my ($i, $oldlen, $newlen, $c) = (0, length($old), length($new)); |
552 |
|
|
my $len = $oldlen < $newlen ? $oldlen : $newlen; |
553 |
|
|
|
554 |
|
|
for ($i = 0; $i < $len; $i++) { |
555 |
|
|
if ($c = substr($old, $i, 1), $c =~ /[\W\d_]/) { |
556 |
|
|
$state = 0; |
557 |
|
|
} elsif (lc $c eq $c) { |
558 |
|
|
substr($new, $i, 1) = lc(substr($new, $i, 1)); |
559 |
|
|
$state = 1; |
560 |
|
|
} else { |
561 |
|
|
substr($new, $i, 1) = uc(substr($new, $i, 1)); |
562 |
|
|
$state = 2; |
563 |
|
|
} |
564 |
|
|
} |
565 |
|
|
# finish up with any remaining new (for when new is longer than old) |
566 |
|
|
if ($newlen > $oldlen) { |
567 |
|
|
if ($state == 1) { |
568 |
|
|
substr($new, $oldlen) = lc(substr($new, $oldlen)); |
569 |
|
|
} elsif ($state == 2) { |
570 |
|
|
substr($new, $oldlen) = uc(substr($new, $oldlen)); |
571 |
|
|
} |
572 |
|
|
} |
573 |
|
|
return $new; |
574 |
|
|
} |
575 |
|
|
|
576 |
|
|
=head2 How can I make C<\w> match national character sets? |
577 |
|
|
X<\w> |
578 |
|
|
|
579 |
|
|
(C<\w> がローカルな文字セットにマッチするようにするには?) |
580 |
|
|
|
581 |
|
|
=begin original |
582 |
|
|
|
583 |
|
|
Put C<use locale;> in your script. The \w character class is taken |
584 |
|
|
from the current locale. |
585 |
|
|
|
586 |
|
|
=end original |
587 |
|
|
|
588 |
|
|
C<use locale;> をスクリプトに書いてください。 |
589 |
|
|
\w 文字クラスが現在のロケールから取られるようになります。 |
590 |
|
|
|
591 |
|
|
=begin original |
592 |
|
|
|
593 |
|
|
See L<perllocale> for details. |
594 |
|
|
|
595 |
|
|
=end original |
596 |
|
|
|
597 |
|
|
詳しくは L<perllocale> を参照してください。 |
598 |
|
|
|
599 |
|
|
=head2 How can I match a locale-smart version of C</[a-zA-Z]/>? |
600 |
|
|
X<alpha> |
601 |
|
|
|
602 |
|
|
(C</[a-zA-Z]/>の locale-smart なバージョンでマッチさせるには?) |
603 |
|
|
|
604 |
|
|
=begin original |
605 |
|
|
|
606 |
|
|
You can use the POSIX character class syntax C</[[:alpha:]]/> |
607 |
|
|
documented in L<perlre>. |
608 |
|
|
|
609 |
|
|
=end original |
610 |
|
|
|
611 |
|
|
L<perlre> で記述されている、POSIX 文字クラス文法 C</[[:alpha:]]/> が |
612 |
|
|
使えます。 |
613 |
|
|
|
614 |
|
|
=begin original |
615 |
|
|
|
616 |
|
|
No matter which locale you are in, the alphabetic characters are |
617 |
|
|
the characters in \w without the digits and the underscore. |
618 |
|
|
As a regex, that looks like C</[^\W\d_]/>. Its complement, |
619 |
|
|
the non-alphabetics, is then everything in \W along with |
620 |
|
|
the digits and the underscore, or C</[\W\d_]/>. |
621 |
|
|
|
622 |
|
|
=end original |
623 |
|
|
|
624 |
|
|
あなたがどこにいるかに関わらず、英文字は \w から数字と下線を除いたものです。 |
625 |
|
|
正規表現としては、これは C</[^\W\d_]/> のようになります。 |
626 |
|
|
その逆である非英字は、\W に含まれる全ての文字に数字と下線を加えたもの、 |
627 |
|
|
つまり C</[\W\d_]/> です。 |
628 |
|
|
|
629 |
|
|
=head2 How can I quote a variable to use in a regex? |
630 |
|
|
X<regex, escaping> X<regexp, escaping> X<regular expression, escaping> |
631 |
|
|
|
632 |
|
|
(正規表現の中で使う変数をクォートするには?) |
633 |
|
|
|
634 |
|
|
=begin original |
635 |
|
|
|
636 |
|
|
The Perl parser will expand $variable and @variable references in |
637 |
|
|
regular expressions unless the delimiter is a single quote. Remember, |
638 |
|
|
too, that the right-hand side of a C<s///> substitution is considered |
639 |
|
|
a double-quoted string (see L<perlop> for more details). Remember |
640 |
|
|
also that any regex special characters will be acted on unless you |
641 |
|
|
precede the substitution with \Q. Here's an example: |
642 |
|
|
|
643 |
|
|
=end original |
644 |
|
|
|
645 |
|
|
Perlの構文解析器(parser)は、区切りがシングルクォーテーションでない限り、 |
646 |
|
|
正規表現の中にある $variable や @variable といったものを展開します。 |
647 |
|
|
C<s///> による置換の右側にあるものはダブルクォーテーションで |
648 |
|
|
括られた文字列とみなされるということを忘れないでください。 |
649 |
|
|
また、すべての正規表現演算子はその前に \Q を置いておかないと、 |
650 |
|
|
正規表現演算子として振る舞うということも忘れないでください。 |
651 |
|
|
以下に例を挙げます。 |
652 |
|
|
|
653 |
|
|
$string = "Placido P. Octopus"; |
654 |
|
|
$regex = "P."; |
655 |
|
|
|
656 |
|
|
$string =~ s/$regex/Polyp/; |
657 |
|
|
# $string is now "Polypacido P. Octopus" |
658 |
|
|
|
659 |
|
|
=begin original |
660 |
|
|
|
661 |
|
|
Because C<.> is special in regular expressions, and can match any |
662 |
|
|
single character, the regex C<P.> here has matched the <Pl> in the |
663 |
|
|
original string. |
664 |
|
|
|
665 |
|
|
=end original |
666 |
|
|
|
667 |
|
|
C<.> 正規表現では特別で、任意の 1 文字にマッチングするので、 |
668 |
|
|
ここでの C<P.> は元の文字列の <Pl> にマッチングします。 |
669 |
|
|
|
670 |
|
|
=begin original |
671 |
|
|
|
672 |
|
|
To escape the special meaning of C<.>, we use C<\Q>: |
673 |
|
|
|
674 |
|
|
=end original |
675 |
|
|
|
676 |
|
|
C<.> の特殊な意味をエスケープするには、C<\Q> を使います: |
677 |
|
|
|
678 |
|
|
$string = "Placido P. Octopus"; |
679 |
|
|
$regex = "P."; |
680 |
|
|
|
681 |
|
|
$string =~ s/\Q$regex/Polyp/; |
682 |
|
|
# $string is now "Placido Polyp Octopus" |
683 |
|
|
|
684 |
|
|
=begin original |
685 |
|
|
|
686 |
|
|
The use of C<\Q> causes the <.> in the regex to be treated as a |
687 |
|
|
regular character, so that C<P.> matches a C<P> followed by a dot. |
688 |
|
|
|
689 |
|
|
=end original |
690 |
|
|
|
691 |
|
|
C<\Q> を使うことによって、正規表現中の C<.> は通常の文字として扱われるので、 |
692 |
|
|
C<P.> は C<P> の後にピリオドがあるものにマッチングします。 |
693 |
|
|
|
694 |
|
|
=head2 What is C</o> really for? |
695 |
|
|
X</o, regular expressions> X<compile, regular expressions> |
696 |
|
|
|
697 |
|
|
(C</o> は実際なんのためのものなのですか?) |
698 |
|
|
|
699 |
|
|
=begin original |
700 |
|
|
|
701 |
|
|
(contributed by brian d foy) |
702 |
|
|
|
703 |
|
|
=end original |
704 |
|
|
|
705 |
|
|
(brian d foy によって寄贈されました) |
706 |
|
|
|
707 |
|
|
=begin original |
708 |
|
|
|
709 |
|
|
The C</o> option for regular expressions (documented in L<perlop> and |
710 |
|
|
L<perlreref>) tells Perl to compile the regular expression only once. |
711 |
|
|
This is only useful when the pattern contains a variable. Perls 5.6 |
712 |
|
|
and later handle this automatically if the pattern does not change. |
713 |
|
|
|
714 |
|
|
=end original |
715 |
|
|
|
716 |
|
|
正規表現の C</o> オプション (L<perlop> と L<perlreref> で文書化されています) |
717 |
|
|
は、正規表現を一度だけコンパイルするように Perl に伝えます。 |
718 |
|
|
これはパターンに変数が含まれている場合にのみ有用です。 |
719 |
|
|
Perls 5.6 以降では、パターンが変わらない場合はこれを自動的に扱います。 |
720 |
|
|
|
721 |
|
|
=begin original |
722 |
|
|
|
723 |
|
|
Since the match operator C<m//>, the substitution operator C<s///>, |
724 |
|
|
and the regular expression quoting operator C<qr//> are double-quotish |
725 |
|
|
constructs, you can interpolate variables into the pattern. See the |
726 |
|
|
answer to "How can I quote a variable to use in a regex?" for more |
727 |
|
|
details. |
728 |
|
|
|
729 |
|
|
=end original |
730 |
|
|
|
731 |
|
|
マッチング演算子 C<m//>, 置換演算子 C<s///>, 正規表現クォート演算子 |
732 |
|
|
C<qr//> はダブルクォート風構造なので、パターン中で変数を展開できます。 |
733 |
|
|
詳細については "How can I quote a variable to use in a regex?" の答えを |
734 |
|
|
参照してください。 |
735 |
|
|
|
736 |
|
|
=begin original |
737 |
|
|
|
738 |
|
|
This example takes a regular expression from the argument list and |
739 |
|
|
prints the lines of input that match it: |
740 |
|
|
|
741 |
|
|
=end original |
742 |
|
|
|
743 |
|
|
この例は正規表現を引数リストから取って、それにマッチングする入力行を |
744 |
|
|
表示します: |
745 |
|
|
|
746 |
|
|
my $pattern = shift @ARGV; |
747 |
|
|
|
748 |
|
|
while( <> ) { |
749 |
|
|
print if m/$pattern/; |
750 |
|
|
} |
751 |
|
|
|
752 |
|
|
=begin original |
753 |
|
|
|
754 |
|
|
Versions of Perl prior to 5.6 would recompile the regular expression |
755 |
|
|
for each iteration, even if C<$pattern> had not changed. The C</o> |
756 |
|
|
would prevent this by telling Perl to compile the pattern the first |
757 |
|
|
time, then reuse that for subsequent iterations: |
758 |
|
|
|
759 |
|
|
=end original |
760 |
|
|
|
761 |
|
|
バージョン 5.6 より前の Perl では、C<$pattern> に変更がなくても反復毎に |
762 |
|
|
正規表現が再コンパイルされます。 |
763 |
|
|
C</o> をつけると、パターンを初回にコンパイルし、引き続く反復では |
764 |
|
|
再利用するように Perl に伝えることで、再コンパイルを防ぎます: |
765 |
|
|
|
766 |
|
|
my $pattern = shift @ARGV; |
767 |
|
|
|
768 |
|
|
while( <> ) { |
769 |
|
|
print if m/$pattern/o; # useful for Perl < 5.6 |
770 |
|
|
} |
771 |
|
|
|
772 |
|
|
=begin original |
773 |
|
|
|
774 |
|
|
In versions 5.6 and later, Perl won't recompile the regular expression |
775 |
|
|
if the variable hasn't changed, so you probably don't need the C</o> |
776 |
|
|
option. It doesn't hurt, but it doesn't help either. If you want any |
777 |
|
|
version of Perl to compile the regular expression only once even if |
778 |
|
|
the variable changes (thus, only using its initial value), you still |
779 |
|
|
need the C</o>. |
780 |
|
|
|
781 |
|
|
=end original |
782 |
|
|
|
783 |
|
|
バージョン 5.6 以降では、変数が変更されていない場合は Perl は正規表現を |
784 |
|
|
再コンパイルしませんので、おそらく C</o> は不要です。 |
785 |
|
|
害はもたらしませんが、助けにもなりません。 |
786 |
|
|
どのバージョンでも、たとえ変数の値が変わっても正規表現を一度だけ |
787 |
|
|
コンパイルするようにしたい場合は、未だに C</o> が必要です。 |
788 |
|
|
|
789 |
|
|
=begin original |
790 |
|
|
|
791 |
|
|
You can watch Perl's regular expression engine at work to verify for |
792 |
|
|
yourself if Perl is recompiling a regular expression. The C<use re |
793 |
|
|
'debug'> pragma (comes with Perl 5.005 and later) shows the details. |
794 |
|
|
With Perls before 5.6, you should see C<re> reporting that its |
795 |
|
|
compiling the regular expression on each iteration. With Perl 5.6 or |
796 |
|
|
later, you should only see C<re> report that for the first iteration. |
797 |
|
|
|
798 |
|
|
=end original |
799 |
|
|
|
800 |
|
|
Perl が正規表現を再コンパイルしたときに自分自身で検証するために、動作中の |
801 |
|
|
Perl の正規表現エンジンを見守ることもできます。 |
802 |
|
|
C<use re 'debug'> プラグマ (Perl 5.005 以降で実装されています) は詳細を |
803 |
|
|
表示します。 |
804 |
|
|
5.6 より前の Perl では、各反復で正規表現がコンパイルされる毎に C<re> の |
805 |
|
|
報告を見ることになります。 |
806 |
|
|
Perl 5.6 以降では、最初の反復でのみ C<re> の報告を見ることになります。 |
807 |
|
|
|
808 |
|
|
use re 'debug'; |
809 |
|
|
|
810 |
|
|
my $regex = 'Perl'; |
811 |
|
|
foreach ( qw(Perl Java Ruby Python) ) { |
812 |
|
|
print STDERR "-" x 73, "\n"; |
813 |
|
|
print STDERR "Trying $_...\n"; |
814 |
|
|
print STDERR "\t$_ is good!\n" if m/$regex/; |
815 |
|
|
} |
816 |
|
|
|
817 |
|
|
=head2 How do I use a regular expression to strip C-style comments from a file? |
818 |
|
|
|
819 |
|
|
(ファイルから、C 形式のコメントを剥ぎ取る(strip)するにはどのように正規表現を使えば良いのでしょうか?) |
820 |
|
|
|
821 |
|
|
=begin original |
822 |
|
|
|
823 |
|
|
While this actually can be done, it's much harder than you'd think. |
824 |
|
|
For example, this one-liner |
825 |
|
|
|
826 |
|
|
=end original |
827 |
|
|
|
828 |
|
|
実際これは可能なのですが、あなたが考えているよりも非常に難しいものです。 |
829 |
|
|
たとえば次の一行野郎 (one-liner) はほとんどの場合にうまく行きますが、 |
830 |
|
|
すべての場合ではありません。 |
831 |
|
|
|
832 |
|
|
perl -0777 -pe 's{/\*.*?\*/}{}gs' foo.c |
833 |
|
|
|
834 |
|
|
=begin original |
835 |
|
|
|
836 |
|
|
will work in many but not all cases. You see, it's too simple-minded for |
837 |
|
|
certain kinds of C programs, in particular, those with what appear to be |
838 |
|
|
comments in quoted strings. For that, you'd need something like this, |
839 |
|
|
created by Jeffrey Friedl and later modified by Fred Curtis. |
840 |
|
|
|
841 |
|
|
=end original |
842 |
|
|
|
843 |
|
|
そう、これは C のプログラムを簡単に考えすぎているのです。 |
844 |
|
|
特に、クォートされた文字列にコメントが出現するということを考慮していません。 |
845 |
|
|
このため、Jeffrey Friedl が作成し、後に Fred Curtis によって修正された |
846 |
|
|
次の例のようなことが必要になります。 |
847 |
|
|
|
848 |
|
|
$/ = undef; |
849 |
|
|
$_ = <>; |
850 |
|
|
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $2 ? $2 : ""#gse; |
851 |
|
|
print; |
852 |
|
|
|
853 |
|
|
=begin original |
854 |
|
|
|
855 |
|
|
This could, of course, be more legibly written with the C</x> modifier, adding |
856 |
|
|
whitespace and comments. Here it is expanded, courtesy of Fred Curtis. |
857 |
|
|
|
858 |
|
|
=end original |
859 |
|
|
|
860 |
|
|
もちろんこれは、C</x> 修飾子を使って空白やコメントを付加することで、 |
861 |
|
|
より読みやすくすることが可能です。 |
862 |
|
|
以下は Fred Curtis の提供による拡張版です。 |
863 |
|
|
|
864 |
|
|
s{ |
865 |
|
|
/\* ## Start of /* ... */ comment |
866 |
|
|
[^*]*\*+ ## Non-* followed by 1-or-more *'s |
867 |
|
|
( |
868 |
|
|
[^/*][^*]*\*+ |
869 |
|
|
)* ## 0-or-more things which don't start with / |
870 |
|
|
## but do end with '*' |
871 |
|
|
/ ## End of /* ... */ comment |
872 |
|
|
|
873 |
|
|
| ## OR various things which aren't comments: |
874 |
|
|
|
875 |
|
|
( |
876 |
|
|
" ## Start of " ... " string |
877 |
|
|
( |
878 |
|
|
\\. ## Escaped char |
879 |
|
|
| ## OR |
880 |
|
|
[^"\\] ## Non "\ |
881 |
|
|
)* |
882 |
|
|
" ## End of " ... " string |
883 |
|
|
|
884 |
|
|
| ## OR |
885 |
|
|
|
886 |
|
|
' ## Start of ' ... ' string |
887 |
|
|
( |
888 |
|
|
\\. ## Escaped char |
889 |
|
|
| ## OR |
890 |
|
|
[^'\\] ## Non '\ |
891 |
|
|
)* |
892 |
|
|
' ## End of ' ... ' string |
893 |
|
|
|
894 |
|
|
| ## OR |
895 |
|
|
|
896 |
|
|
. ## Anything other char |
897 |
|
|
[^/"'\\]* ## Chars which doesn't start a comment, string or escape |
898 |
|
|
) |
899 |
|
|
}{defined $2 ? $2 : ""}gxse; |
900 |
|
|
|
901 |
|
|
=begin original |
902 |
|
|
|
903 |
|
|
A slight modification also removes C++ comments, possibly spanning multiple lines |
904 |
|
|
using a continuation character: |
905 |
|
|
|
906 |
|
|
=end original |
907 |
|
|
|
908 |
|
|
(継続文字を使って複数行にわたっていない限りは) |
909 |
|
|
少しの変更で、おそらくは継続文字を使った複数行にわたるものも含む、 |
910 |
|
|
C++ コメントも除去します: |
911 |
|
|
|
912 |
|
|
s#/\*[^*]*\*+([^/*][^*]*\*+)*/|//([^\\]|[^\n][\n]?)*?\n|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|.[^/"'\\]*)#defined $3 ? $3 : ""#gse; |
913 |
|
|
|
914 |
|
|
=head2 Can I use Perl regular expressions to match balanced text? |
915 |
|
|
X<regex, matching balanced test> X<regexp, matching balanced test> |
916 |
|
|
X<regular expression, matching balanced test> X<possessive> X<PARNO> |
917 |
|
|
X<Text::Balanced> X<Regexp::Common> X<backtracking> X<recursion> |
918 |
|
|
|
919 |
|
|
(Perl の正規表現をバランスされたテキストのマッチングに使えますか?) |
920 |
|
|
|
921 |
|
|
=begin original |
922 |
|
|
|
923 |
|
|
(contributed by brian d foy) |
924 |
|
|
|
925 |
|
|
=end original |
926 |
|
|
|
927 |
|
|
(brian d foy によって寄贈されました) |
928 |
|
|
|
929 |
|
|
=begin original |
930 |
|
|
|
931 |
|
|
Your first try should probably be the L<Text::Balanced> module, which |
932 |
|
|
is in the Perl standard library since Perl 5.8. It has a variety of |
933 |
|
|
functions to deal with tricky text. The L<Regexp::Common> module can |
934 |
|
|
also help by providing canned patterns you can use. |
935 |
|
|
|
936 |
|
|
=end original |
937 |
|
|
|
938 |
|
|
おそらく、まずはじめに試すべきなのは、Perl 5.8 から Perl 標準ライブラリに |
939 |
|
|
なっている L<Text::Balanced> モジュールです。 |
940 |
|
|
これには扱いにくい文章を扱うための様々な関数があります。 |
941 |
|
|
L<Regexp::Common> モジュールも、すぐ使えるパターンを提供することで |
942 |
|
|
手助けしてくれます。 |
943 |
|
|
|
944 |
|
|
=begin original |
945 |
|
|
|
946 |
|
|
As of Perl 5.10, you can match balanced text with regular expressions |
947 |
|
|
using recursive patterns. Before Perl 5.10, you had to resort to |
948 |
|
|
various tricks such as using Perl code in C<(??{})> sequences. |
949 |
|
|
|
950 |
|
|
=end original |
951 |
|
|
|
952 |
|
|
Perl 5.10 以降では、再帰パターンを使って正規表現でバランスされた |
953 |
|
|
テキストをマッチングすることが出来ます。 |
954 |
|
|
Perl 5.10 以前では、C<(??{})> シーケンス内で Perl コードを使うといった |
955 |
|
|
さまざまな技を使う必要があります。 |
956 |
|
|
|
957 |
|
|
=begin original |
958 |
|
|
|
959 |
|
|
Here's an example using a recursive regular expression. The goal is to |
960 |
|
|
capture all of the text within angle brackets, including the text in |
961 |
|
|
nested angle brackets. This sample text has two "major" groups: a |
962 |
|
|
group with one level of nesting and a group with two levels of |
963 |
|
|
nesting. There are five total groups in angle brackets: |
964 |
|
|
|
965 |
|
|
=end original |
966 |
|
|
|
967 |
|
|
以下は再帰的正規表現を使った例です。 |
968 |
|
|
ゴールは、(ネストしたものを含む)山かっこ内の全てのテキストを |
969 |
|
|
捕らえることです。 |
970 |
|
|
サンプルの文章には二つの「主な」グループがあります: 1 レベルの |
971 |
|
|
ネストがあるものと、2 レベルのネストがあるものです。 |
972 |
|
|
これは全部で五つの山かっこグループがあります: |
973 |
|
|
|
974 |
|
|
I have some <brackets in <nested brackets> > and |
975 |
|
|
<another group <nested once <nested twice> > > |
976 |
|
|
and that's it. |
977 |
|
|
|
978 |
|
|
=begin original |
979 |
|
|
|
980 |
|
|
The regular expression to match the balanced text uses two new (to |
981 |
|
|
Perl 5.10) regular expression features. These are covered in L<perlre> |
982 |
|
|
and this example is a modified version of one in that documentation. |
983 |
|
|
|
984 |
|
|
=end original |
985 |
|
|
|
986 |
|
|
バランスされたテキストにマッチングする正規表現は二つの新しい |
987 |
|
|
(Perl 5.10 以降の)正規表現の機能を使います。 |
988 |
|
|
これらは L<perlre> で説明されていて、この例はその文書にあるものの |
989 |
|
|
修正版です。 |
990 |
|
|
|
991 |
|
|
=begin original |
992 |
|
|
|
993 |
|
|
First, adding the new possessive C<+> to any quantifier finds the |
994 |
|
|
longest match and does not backtrack. That's important since you want |
995 |
|
|
to handle any angle brackets through the recursion, not backtracking. |
996 |
|
|
The group C<< [^<>]++ >> finds one or more non-angle brackets without |
997 |
|
|
backtracking. |
998 |
|
|
|
999 |
|
|
=end original |
1000 |
|
|
|
1001 |
|
|
まず、絶対量指定子を追加することで、 |
1002 |
|
|
最大マッチングを行って、バックトラックをしません。 |
1003 |
|
|
これは、山かっこをバックトラッキングではなく再帰で扱いたいので |
1004 |
|
|
重要です。 |
1005 |
|
|
グループ C<< [^<>]++ >> は、一つまたは複数の、山かっこでないものを |
1006 |
|
|
バックトラッキングなしで探し出します。 |
1007 |
|
|
|
1008 |
|
|
=begin original |
1009 |
|
|
|
1010 |
|
|
Second, the new C<(?PARNO)> refers to the sub-pattern in the |
1011 |
|
|
particular capture group given by C<PARNO>. In the following regex, |
1012 |
|
|
the first capture group finds (and remembers) the balanced text, and |
1013 |
|
|
you need that same pattern within the first buffer to get past the |
1014 |
|
|
nested text. That's the recursive part. The C<(?1)> uses the pattern |
1015 |
|
|
in the outer capture group as an independent part of the regex. |
1016 |
|
|
|
1017 |
|
|
=end original |
1018 |
|
|
|
1019 |
|
|
次に、新しい C<(?PARNO)> は、C<PARNO> で与えられる特定の捕捉バッファ内の |
1020 |
|
|
副パターンを参照します。 |
1021 |
|
|
以下の正規表現では、最初の捕捉バッファがバランスされたテキストを |
1022 |
|
|
発見し(さらに保存し)、ネストしたテキストを調べるために最初のバッファ内に |
1023 |
|
|
同じパターンを適用する必要があります。 |
1024 |
|
|
C<(?1)> は、外側の捕捉バッファのパターンを正規表現内の |
1025 |
|
|
独立した部分として使います。 |
1026 |
|
|
|
1027 |
|
|
=begin original |
1028 |
|
|
|
1029 |
|
|
Putting it all together, you have: |
1030 |
|
|
|
1031 |
|
|
=end original |
1032 |
|
|
|
1033 |
|
|
これを全てまとめると: |
1034 |
|
|
|
1035 |
|
|
#!/usr/local/bin/perl5.10.0 |
1036 |
|
|
|
1037 |
|
|
my $string =<<"HERE"; |
1038 |
|
|
I have some <brackets in <nested brackets> > and |
1039 |
|
|
<another group <nested once <nested twice> > > |
1040 |
|
|
and that's it. |
1041 |
|
|
HERE |
1042 |
|
|
|
1043 |
|
|
my @groups = $string =~ m/ |
1044 |
|
|
( # start of capture group 1 |
1045 |
|
|
< # match an opening angle bracket |
1046 |
|
|
(?: |
1047 |
|
|
[^<>]++ # one or more non angle brackets, non backtracking |
1048 |
|
|
| |
1049 |
|
|
(?1) # found < or >, so recurse to capture group 1 |
1050 |
|
|
)* |
1051 |
|
|
> # match a closing angle bracket |
1052 |
|
|
) # end of capture group 1 |
1053 |
|
|
/xg; |
1054 |
|
|
|
1055 |
|
|
$" = "\n\t"; |
1056 |
|
|
print "Found:\n\t@groups\n"; |
1057 |
|
|
|
1058 |
|
|
=begin original |
1059 |
|
|
|
1060 |
|
|
The output shows that Perl found the two major groups: |
1061 |
|
|
|
1062 |
|
|
=end original |
1063 |
|
|
|
1064 |
|
|
Perl が二つの主なグループを発見したことが出力されます: |
1065 |
|
|
|
1066 |
|
|
Found: |
1067 |
|
|
<brackets in <nested brackets> > |
1068 |
|
|
<another group <nested once <nested twice> > > |
1069 |
|
|
|
1070 |
|
|
=begin original |
1071 |
|
|
|
1072 |
|
|
With a little extra work, you can get the all of the groups in angle |
1073 |
|
|
brackets even if they are in other angle brackets too. Each time you |
1074 |
|
|
get a balanced match, remove its outer delimiter (that's the one you |
1075 |
|
|
just matched so don't match it again) and add it to a queue of strings |
1076 |
|
|
to process. Keep doing that until you get no matches: |
1077 |
|
|
|
1078 |
|
|
=end original |
1079 |
|
|
|
1080 |
|
|
もう少し作業すれば、たとえ他の山かっこがあっても、全ての山かっこの |
1081 |
|
|
グループを得られます。 |
1082 |
|
|
バランスされたマッチングが得られる毎に、外側のデリミタを取り除いて |
1083 |
|
|
(これは今マッチングしたモノにまたマッチングしないようにするためです)、 |
1084 |
|
|
処理する文字列のキューに追加します。 |
1085 |
|
|
これを、マッチングしなくなるまで繰り返します: |
1086 |
|
|
|
1087 |
|
|
#!/usr/local/bin/perl5.10.0 |
1088 |
|
|
|
1089 |
|
|
my @queue =<<"HERE"; |
1090 |
|
|
I have some <brackets in <nested brackets> > and |
1091 |
|
|
<another group <nested once <nested twice> > > |
1092 |
|
|
and that's it. |
1093 |
|
|
HERE |
1094 |
|
|
|
1095 |
|
|
my $regex = qr/ |
1096 |
|
|
( # start of bracket 1 |
1097 |
|
|
< # match an opening angle bracket |
1098 |
|
|
(?: |
1099 |
|
|
[^<>]++ # one or more non angle brackets, non backtracking |
1100 |
|
|
| |
1101 |
|
|
(?1) # recurse to bracket 1 |
1102 |
|
|
)* |
1103 |
|
|
> # match a closing angle bracket |
1104 |
|
|
) # end of bracket 1 |
1105 |
|
|
/x; |
1106 |
|
|
|
1107 |
|
|
$" = "\n\t"; |
1108 |
|
|
|
1109 |
|
|
while( @queue ) { |
1110 |
|
|
my $string = shift @queue; |
1111 |
|
|
|
1112 |
|
|
my @groups = $string =~ m/$regex/g; |
1113 |
|
|
print "Found:\n\t@groups\n\n" if @groups; |
1114 |
|
|
|
1115 |
|
|
unshift @queue, map { s/^<//; s/>$//; $_ } @groups; |
1116 |
|
|
} |
1117 |
|
|
|
1118 |
|
|
=begin original |
1119 |
|
|
|
1120 |
|
|
The output shows all of the groups. The outermost matches show up |
1121 |
|
|
first and the nested matches so up later: |
1122 |
|
|
|
1123 |
|
|
=end original |
1124 |
|
|
|
1125 |
|
|
全てのグループが出力されます。 |
1126 |
|
|
一番外側のマッチングが最初に表示され、ネストしたマッチングはその後に |
1127 |
|
|
なります: |
1128 |
|
|
|
1129 |
|
|
Found: |
1130 |
|
|
<brackets in <nested brackets> > |
1131 |
|
|
<another group <nested once <nested twice> > > |
1132 |
|
|
|
1133 |
|
|
Found: |
1134 |
|
|
<nested brackets> |
1135 |
|
|
|
1136 |
|
|
Found: |
1137 |
|
|
<nested once <nested twice> > |
1138 |
|
|
|
1139 |
|
|
Found: |
1140 |
|
|
<nested twice> |
1141 |
|
|
|
1142 |
|
|
=head2 What does it mean that regexes are greedy? How can I get around it? |
1143 |
|
|
X<greedy> X<greediness> |
1144 |
|
|
|
1145 |
|
|
(正規表現が貪欲(greedy)であるとはどういうことですか?) |
1146 |
|
|
|
1147 |
|
|
=begin original |
1148 |
|
|
|
1149 |
|
|
Most people mean that greedy regexes match as much as they can. |
1150 |
|
|
Technically speaking, it's actually the quantifiers (C<?>, C<*>, C<+>, |
1151 |
|
|
C<{}>) that are greedy rather than the whole pattern; Perl prefers local |
1152 |
|
|
greed and immediate gratification to overall greed. To get non-greedy |
1153 |
|
|
versions of the same quantifiers, use (C<??>, C<*?>, C<+?>, C<{}?>). |
1154 |
|
|
|
1155 |
|
|
=end original |
1156 |
|
|
|
1157 |
|
|
ほとんどの人が、貪欲正規表現(greedy regexps)は可能な限りマッチすると |
1158 |
|
|
考えています。 |
1159 |
|
|
技術的には、量指定子(C<?>, C<*>, C<+>, C<{}>) はパターン全体よりも貪欲です。 |
1160 |
|
|
Perl は、全体的な貪欲性よりも局所貪欲性と即時の満足性を好みます。 |
1161 |
|
|
同じ量指定子の non-greedy バージョンを得るには、 |
1162 |
|
|
C<??>, C<*?>, C<+?>, C<{}?>を使います。 |
1163 |
|
|
|
1164 |
|
|
=begin original |
1165 |
|
|
|
1166 |
|
|
An example: |
1167 |
|
|
|
1168 |
|
|
=end original |
1169 |
|
|
|
1170 |
|
|
例: |
1171 |
|
|
|
1172 |
|
|
my $s1 = my $s2 = "I am very very cold"; |
1173 |
|
|
$s1 =~ s/ve.*y //; # I am cold |
1174 |
|
|
$s2 =~ s/ve.*?y //; # I am very cold |
1175 |
|
|
|
1176 |
|
|
=begin original |
1177 |
|
|
|
1178 |
|
|
Notice how the second substitution stopped matching as soon as it |
1179 |
|
|
encountered "y ". The C<*?> quantifier effectively tells the regular |
1180 |
|
|
expression engine to find a match as quickly as possible and pass |
1181 |
|
|
control on to whatever is next in line, as you would if you were |
1182 |
|
|
playing hot potato. |
1183 |
|
|
|
1184 |
|
|
=end original |
1185 |
|
|
|
1186 |
|
|
二番目の置換が、“y ”を見つけてすぐにマッチングを中断していることに |
1187 |
|
|
注目してください。 |
1188 |
|
|
量指定子 C<*?> は正規表現エンジンに対して、あなたが熱いジャガイモを |
1189 |
|
|
扱っているときのように、可能な限り早くマッチするものを見つけて制御を次の行に |
1190 |
|
|
渡すように効果的に指示します。 |
1191 |
|
|
|
1192 |
|
|
=head2 How do I process each word on each line? |
1193 |
|
|
X<word> |
1194 |
|
|
|
1195 |
|
|
(各行の単語単位に処理をするにはどうすれば良いですか?) |
1196 |
|
|
|
1197 |
|
|
=begin original |
1198 |
|
|
|
1199 |
|
|
Use the split function: |
1200 |
|
|
|
1201 |
|
|
=end original |
1202 |
|
|
|
1203 |
|
|
split 関数を使います: |
1204 |
|
|
|
1205 |
|
|
while (<>) { |
1206 |
|
|
foreach my $word ( split ) { |
1207 |
|
|
# do something with $word here |
1208 |
|
|
} |
1209 |
|
|
} |
1210 |
|
|
|
1211 |
|
|
=begin original |
1212 |
|
|
|
1213 |
|
|
Note that this isn't really a word in the English sense; it's just |
1214 |
|
|
chunks of consecutive non-whitespace characters. |
1215 |
|
|
|
1216 |
|
|
=end original |
1217 |
|
|
|
1218 |
|
|
これは実際には英語でいうところの語ではないことに注意してください。 |
1219 |
|
|
これは、単なる連続した空白でない文字の塊です。 |
1220 |
|
|
|
1221 |
|
|
=begin original |
1222 |
|
|
|
1223 |
|
|
To work with only alphanumeric sequences (including underscores), you |
1224 |
|
|
might consider |
1225 |
|
|
|
1226 |
|
|
=end original |
1227 |
|
|
|
1228 |
|
|
アルファベットもしくは数字の並びのみを対象とするには以下のようにして |
1229 |
|
|
できます。 |
1230 |
|
|
|
1231 |
|
|
while (<>) { |
1232 |
|
|
foreach $word (m/(\w+)/g) { |
1233 |
|
|
# do something with $word here |
1234 |
|
|
} |
1235 |
|
|
} |
1236 |
|
|
|
1237 |
|
|
=head2 How can I print out a word-frequency or line-frequency summary? |
1238 |
|
|
|
1239 |
|
|
(語の出現頻度や行の出現頻度のまとめを出力するには?) |
1240 |
|
|
|
1241 |
|
|
=begin original |
1242 |
|
|
|
1243 |
|
|
To do this, you have to parse out each word in the input stream. We'll |
1244 |
|
|
pretend that by word you mean chunk of alphabetics, hyphens, or |
1245 |
|
|
apostrophes, rather than the non-whitespace chunk idea of a word given |
1246 |
|
|
in the previous question: |
1247 |
|
|
|
1248 |
|
|
=end original |
1249 |
|
|
|
1250 |
|
|
これを行うためには、入力ストリームにある単語のそれぞれについて解析する |
1251 |
|
|
必要があります。 |
1252 |
|
|
私たちはここで、一つ前の質問と同様に、非空白文字の塊を語と |
1253 |
|
|
するのではなく、英字、ハイフン、アポストロフィ、の塊を語とします: |
1254 |
|
|
|
1255 |
|
|
my (%seen); |
1256 |
|
|
while (<>) { |
1257 |
|
|
while ( /(\b[^\W_\d][\w'-]+\b)/g ) { # misses "`sheep'" |
1258 |
|
|
$seen{$1}++; |
1259 |
|
|
} |
1260 |
|
|
} |
1261 |
|
|
|
1262 |
|
|
while ( my ($word, $count) = each %seen ) { |
1263 |
|
|
print "$count $word\n"; |
1264 |
|
|
} |
1265 |
|
|
|
1266 |
|
|
=begin original |
1267 |
|
|
|
1268 |
|
|
If you wanted to do the same thing for lines, you wouldn't need a |
1269 |
|
|
regular expression: |
1270 |
|
|
|
1271 |
|
|
=end original |
1272 |
|
|
|
1273 |
|
|
同じことを行に対して行いたいのであれば、正規表現は必要ないでしょう。 |
1274 |
|
|
|
1275 |
|
|
my (%seen); |
1276 |
|
|
|
1277 |
|
|
while (<>) { |
1278 |
|
|
$seen{$_}++; |
1279 |
|
|
} |
1280 |
|
|
|
1281 |
|
|
while ( my ($line, $count) = each %seen ) { |
1282 |
|
|
print "$count $line"; |
1283 |
|
|
} |
1284 |
|
|
|
1285 |
|
|
=begin original |
1286 |
|
|
|
1287 |
|
|
If you want these output in a sorted order, see L<perlfaq4>: "How do I |
1288 |
|
|
sort a hash (optionally by value instead of key)?". |
1289 |
|
|
|
1290 |
|
|
=end original |
1291 |
|
|
|
1292 |
|
|
ソートされた順序で出力したいのなら、L<perlfaq4>: "How do I |
1293 |
|
|
sort a hash (optionally by value instead of key)?" を参照してください。 |
1294 |
|
|
|
1295 |
|
|
=head2 How can I do approximate matching? |
1296 |
|
|
X<match, approximate> X<matching, approximate> |
1297 |
|
|
|
1298 |
|
|
(曖昧なマッチング (approximate matching) はどうやればできますか?) |
1299 |
|
|
|
1300 |
|
|
=begin original |
1301 |
|
|
|
1302 |
|
|
See the module L<String::Approx> available from CPAN. |
1303 |
|
|
|
1304 |
|
|
=end original |
1305 |
|
|
|
1306 |
|
|
CPAN で入手できる L<String::Approx> モジュールを参照してください。 |
1307 |
|
|
|
1308 |
|
|
=head2 How do I efficiently match many regular expressions at once? |
1309 |
|
|
X<regex, efficiency> X<regexp, efficiency> |
1310 |
|
|
X<regular expression, efficiency> |
1311 |
|
|
|
1312 |
|
|
(たくさんの正規表現を一度に効率良くマッチングするには?) |
1313 |
|
|
|
1314 |
|
|
=begin original |
1315 |
|
|
|
1316 |
|
|
(contributed by brian d foy) |
1317 |
|
|
|
1318 |
|
|
=end original |
1319 |
|
|
|
1320 |
|
|
(brian d foy によって寄贈されました) |
1321 |
|
|
|
1322 |
|
|
=begin original |
1323 |
|
|
|
1324 |
|
|
If you have Perl 5.10 or later, this is almost trivial. You just smart |
1325 |
|
|
match against an array of regular expression objects: |
1326 |
|
|
|
1327 |
|
|
=end original |
1328 |
|
|
|
1329 |
|
|
Perl 5.10 以降では、これはほぼささいな問題です。 |
1330 |
|
|
単に正規表現オブジェクトの配列に対してスマートマッチングします: |
1331 |
|
|
|
1332 |
|
|
my @patterns = ( qr/Fr.d/, qr/B.rn.y/, qr/W.lm./ ); |
1333 |
|
|
|
1334 |
|
|
if( $string ~~ @patterns ) { |
1335 |
|
|
... |
1336 |
|
|
}; |
1337 |
|
|
|
1338 |
|
|
=begin original |
1339 |
|
|
|
1340 |
|
|
The smart match stops when it finds a match, so it doesn't have to try |
1341 |
|
|
every expression. |
1342 |
|
|
|
1343 |
|
|
=end original |
1344 |
|
|
|
1345 |
|
|
マッチングするとスマートマッチングは停止するので、全ての正規表現を |
1346 |
|
|
試す必要はありません。 |
1347 |
|
|
|
1348 |
|
|
=begin original |
1349 |
|
|
|
1350 |
|
|
Earlier than Perl 5.10, you have a bit of work to do. You want to |
1351 |
|
|
avoid compiling a regular expression every time you want to match it. |
1352 |
|
|
In this example, perl must recompile the regular expression for every |
1353 |
|
|
iteration of the C<foreach> loop since it has no way to know what |
1354 |
|
|
C<$pattern> will be: |
1355 |
|
|
|
1356 |
|
|
=end original |
1357 |
|
|
|
1358 |
|
|
Perl 5.10 より前では、少し作業が必要です。 |
1359 |
|
|
マッチングを行う毎に Perl が正規表現をコンパイルすることを避けてください。 |
1360 |
|
|
この例の場合、C<$pattern> が何者なのかを知る方法がないので、perl は |
1361 |
|
|
C<foreach> ループの反復毎に正規表現を再コンパイルしなければなりません: |
1362 |
|
|
|
1363 |
|
|
my @patterns = qw( foo bar baz ); |
1364 |
|
|
|
1365 |
|
|
LINE: while( <DATA> ) { |
1366 |
|
|
foreach $pattern ( @patterns ) { |
1367 |
|
|
if( /\b$pattern\b/i ) { |
1368 |
|
|
print; |
1369 |
|
|
next LINE; |
1370 |
|
|
} |
1371 |
|
|
} |
1372 |
|
|
} |
1373 |
|
|
|
1374 |
|
|
=begin original |
1375 |
|
|
|
1376 |
|
|
The C<qr//> operator showed up in perl 5.005. It compiles a regular |
1377 |
|
|
expression, but doesn't apply it. When you use the pre-compiled |
1378 |
|
|
version of the regex, perl does less work. In this example, I inserted |
1379 |
|
|
a C<map> to turn each pattern into its pre-compiled form. The rest of |
1380 |
|
|
the script is the same, but faster: |
1381 |
|
|
|
1382 |
|
|
=end original |
1383 |
|
|
|
1384 |
|
|
C<qr//> 演算子は perl 5.005 で現れました。 |
1385 |
|
|
これは正規表現をコンパイルしますが、適用はしません。 |
1386 |
|
|
プリコンパイルされた正規表現を使うと、perl の作業は減ります。 |
1387 |
|
|
この例では、各パターンをプリコンパイルされた形式に変換するための |
1388 |
|
|
C<map()> を挿入しています。 |
1389 |
|
|
スクリプトの残りの部分は同じですが、より速いです: |
1390 |
|
|
|
1391 |
|
|
my @patterns = map { qr/\b$_\b/i } qw( foo bar baz ); |
1392 |
|
|
|
1393 |
|
|
LINE: while( <> ) { |
1394 |
|
|
foreach $pattern ( @patterns ) { |
1395 |
|
|
if( /$pattern/ ) { |
1396 |
|
|
print; |
1397 |
|
|
next LINE; |
1398 |
|
|
} |
1399 |
|
|
} |
1400 |
|
|
} |
1401 |
|
|
|
1402 |
|
|
=begin original |
1403 |
|
|
|
1404 |
|
|
In some cases, you may be able to make several patterns into a single |
1405 |
|
|
regular expression. Beware of situations that require backtracking |
1406 |
|
|
though. |
1407 |
|
|
|
1408 |
|
|
=end original |
1409 |
|
|
|
1410 |
|
|
いくつかの場合では、複数のパターンを一つの正規表現にできるかもしれません。 |
1411 |
|
|
しかし、バックトラッキングが必要になる状況に注意してください。 |
1412 |
|
|
|
1413 |
|
|
my $regex = join '|', qw( foo bar baz ); |
1414 |
|
|
|
1415 |
|
|
LINE: while( <> ) { |
1416 |
|
|
print if /\b(?:$regex)\b/i; |
1417 |
|
|
} |
1418 |
|
|
|
1419 |
|
|
=begin original |
1420 |
|
|
|
1421 |
|
|
For more details on regular expression efficiency, see I<Mastering |
1422 |
|
|
Regular Expressions> by Jeffrey Friedl. He explains how the regular |
1423 |
|
|
expressions engine works and why some patterns are surprisingly |
1424 |
|
|
inefficient. Once you understand how perl applies regular expressions, |
1425 |
|
|
you can tune them for individual situations. |
1426 |
|
|
|
1427 |
|
|
=end original |
1428 |
|
|
|
1429 |
|
|
正規表現の効率に関するさらなる詳細については、Jeffrey Friedl による |
1430 |
|
|
I<Mastering Regular Expressions> を参照してください。 |
1431 |
|
|
彼は、どのように正規表現エンジンが動作するかと、なぜある種のパターンが |
1432 |
|
|
驚くほど非効率かについて説明しています。 |
1433 |
|
|
perl がどのように正規表現を適用するかを理解すれば、これらを個々の状況に |
1434 |
|
|
調整できます。 |
1435 |
|
|
|
1436 |
|
|
=head2 Why don't word-boundary searches with C<\b> work for me? |
1437 |
|
|
X<\b> |
1438 |
|
|
|
1439 |
|
|
(なぜ C<\b> を使った単語境界の検索がうまく行かないのでしょうか?) |
1440 |
|
|
|
1441 |
|
|
=begin original |
1442 |
|
|
|
1443 |
|
|
(contributed by brian d foy) |
1444 |
|
|
|
1445 |
|
|
=end original |
1446 |
|
|
|
1447 |
|
|
(brian d foy によって寄贈されました) |
1448 |
|
|
|
1449 |
|
|
=begin original |
1450 |
|
|
|
1451 |
|
|
Ensure that you know what \b really does: it's the boundary between a |
1452 |
|
|
word character, \w, and something that isn't a word character. That |
1453 |
|
|
thing that isn't a word character might be \W, but it can also be the |
1454 |
|
|
start or end of the string. |
1455 |
|
|
|
1456 |
|
|
=end original |
1457 |
|
|
|
1458 |
|
|
実際に \b が何を行うかをしっかり理解してください: |
1459 |
|
|
これは単語文字 (\w) と、単語文字でない何かとの境界です。 |
1460 |
|
|
単語文字でないというのは \W かもしれませんが、文字列の最初と最後にも |
1461 |
|
|
あります。 |
1462 |
|
|
|
1463 |
|
|
=begin original |
1464 |
|
|
|
1465 |
|
|
It's not (not!) the boundary between whitespace and non-whitespace, |
1466 |
|
|
and it's not the stuff between words we use to create sentences. |
1467 |
|
|
|
1468 |
|
|
=end original |
1469 |
|
|
|
1470 |
|
|
これは空白と非空白との境界ではなく(違うんです!)、私たちが文を作るのに |
1471 |
|
|
使う単語の間のものではありません。 |
1472 |
|
|
|
1473 |
|
|
=begin original |
1474 |
|
|
|
1475 |
|
|
In regex speak, a word boundary (\b) is a "zero width assertion", |
1476 |
|
|
meaning that it doesn't represent a character in the string, but a |
1477 |
|
|
condition at a certain position. |
1478 |
|
|
|
1479 |
|
|
=end original |
1480 |
|
|
|
1481 |
|
|
正規表現的に言うと、単語境界は (\b) は「ゼロ幅アサーション」です; |
1482 |
|
|
これは文字列中の文字ではなく、ある位置での条件を表現しています。 |
1483 |
|
|
|
1484 |
|
|
=begin original |
1485 |
|
|
|
1486 |
|
|
For the regular expression, /\bPerl\b/, there has to be a word |
1487 |
|
|
boundary before the "P" and after the "l". As long as something other |
1488 |
|
|
than a word character precedes the "P" and succeeds the "l", the |
1489 |
|
|
pattern will match. These strings match /\bPerl\b/. |
1490 |
|
|
|
1491 |
|
|
=end original |
1492 |
|
|
|
1493 |
|
|
正規表現 /\bPerl\b/ では、"P" の前と "l" の後に単語境界がなければなりません。 |
1494 |
|
|
"P" の前と "l" の後に単語文字以外の何かがある限り、このパターンは |
1495 |
|
|
マッチングします。 |
1496 |
|
|
以下の文字列は /\bPerl\b/ にマッチングします。 |
1497 |
|
|
|
1498 |
|
|
"Perl" # no word char before P or after l |
1499 |
|
|
"Perl " # same as previous (space is not a word char) |
1500 |
|
|
"'Perl'" # the ' char is not a word char |
1501 |
|
|
"Perl's" # no word char before P, non-word char after "l" |
1502 |
|
|
|
1503 |
|
|
=begin original |
1504 |
|
|
|
1505 |
|
|
These strings do not match /\bPerl\b/. |
1506 |
|
|
|
1507 |
|
|
=end original |
1508 |
|
|
|
1509 |
|
|
これらの文字列は /\bPerl\b/ にマッチングしません。 |
1510 |
|
|
|
1511 |
|
|
"Perl_" # _ is a word char! |
1512 |
|
|
"Perler" # no word char before P, but one after l |
1513 |
|
|
|
1514 |
|
|
=begin original |
1515 |
|
|
|
1516 |
|
|
You don't have to use \b to match words though. You can look for |
1517 |
|
|
non-word characters surrounded by word characters. These strings |
1518 |
|
|
match the pattern /\b'\b/. |
1519 |
|
|
|
1520 |
|
|
=end original |
1521 |
|
|
|
1522 |
|
|
しかし、単語にマッチングさせるために \b を使う必要はありません。 |
1523 |
|
|
単語文字に囲まれた非単語文字を探すのに使えます。 |
1524 |
|
|
これらの文字列は、パターン /\b'\b/ にマッチングします。 |
1525 |
|
|
|
1526 |
|
|
"don't" # the ' char is surrounded by "n" and "t" |
1527 |
|
|
"qep'a'" # the ' char is surrounded by "p" and "a" |
1528 |
|
|
|
1529 |
|
|
=begin original |
1530 |
|
|
|
1531 |
|
|
These strings do not match /\b'\b/. |
1532 |
|
|
|
1533 |
|
|
=end original |
1534 |
|
|
|
1535 |
|
|
これらの文字列は /\b'\b/ にマッチングしません。 |
1536 |
|
|
|
1537 |
|
|
"foo'" # there is no word char after non-word ' |
1538 |
|
|
|
1539 |
|
|
=begin original |
1540 |
|
|
|
1541 |
|
|
You can also use the complement of \b, \B, to specify that there |
1542 |
|
|
should not be a word boundary. |
1543 |
|
|
|
1544 |
|
|
=end original |
1545 |
|
|
|
1546 |
|
|
単語境界ではないということを指定するために、\b の逆である \B も使えます。 |
1547 |
|
|
|
1548 |
|
|
=begin original |
1549 |
|
|
|
1550 |
|
|
In the pattern /\Bam\B/, there must be a word character before the "a" |
1551 |
|
|
and after the "m". These patterns match /\Bam\B/: |
1552 |
|
|
|
1553 |
|
|
=end original |
1554 |
|
|
|
1555 |
|
|
パターン /\Bam\B/ では、"a" の前と "m" の後ろに単語文字が必要です。 |
1556 |
|
|
これらはパターン /\Bam\B/ にマッチングします: |
1557 |
|
|
|
1558 |
|
|
"llama" # "am" surrounded by word chars |
1559 |
|
|
"Samuel" # same |
1560 |
|
|
|
1561 |
|
|
=begin original |
1562 |
|
|
|
1563 |
|
|
These strings do not match /\Bam\B/ |
1564 |
|
|
|
1565 |
|
|
=end original |
1566 |
|
|
|
1567 |
|
|
これらの文字列は /\Bam\B/ にマッチングしません。 |
1568 |
|
|
|
1569 |
|
|
"Sam" # no word boundary before "a", but one after "m" |
1570 |
|
|
"I am Sam" # "am" surrounded by non-word chars |
1571 |
|
|
|
1572 |
|
|
=head2 Why does using $&, $`, or $' slow my program down? |
1573 |
|
|
X<$MATCH> X<$&> X<$POSTMATCH> X<$'> X<$PREMATCH> X<$`> |
1574 |
|
|
|
1575 |
|
|
(なぜ $&, $`, $' を使うとプログラムが遅くなるの?) |
1576 |
|
|
|
1577 |
|
|
=begin original |
1578 |
|
|
|
1579 |
|
|
(contributed by Anno Siegel) |
1580 |
|
|
|
1581 |
|
|
=end original |
1582 |
|
|
|
1583 |
|
|
(Anno Siegel によって寄贈されました) |
1584 |
|
|
|
1585 |
|
|
=begin original |
1586 |
|
|
|
1587 |
|
|
Once Perl sees that you need one of these variables anywhere in the |
1588 |
|
|
program, it provides them on each and every pattern match. That means |
1589 |
|
|
that on every pattern match the entire string will be copied, part of it |
1590 |
|
|
to $`, part to $&, and part to $'. Thus the penalty is most severe with |
1591 |
|
|
long strings and patterns that match often. Avoid $&, $', and $` if you |
1592 |
|
|
can, but if you can't, once you've used them at all, use them at will |
1593 |
|
|
because you've already paid the price. Remember that some algorithms |
1594 |
|
|
really appreciate them. As of the 5.005 release, the $& variable is no |
1595 |
|
|
longer "expensive" the way the other two are. |
1596 |
|
|
|
1597 |
|
|
=end original |
1598 |
|
|
|
1599 |
|
|
プログラムのどこかでそういった変数が使われているのを見つけてしまうと、 |
1600 |
|
|
Perl はすべてのパターンマッチングに対してそれに対処することを |
1601 |
|
|
やらなければなりません。 |
1602 |
|
|
これは、全てのパターンマッチングに置いて、一部は $` に、一部は $& に、 |
1603 |
|
|
一部は $' に、という形で文字列全体がコピーされるということを意味します。 |
1604 |
|
|
従って、ペナルティは長い文字列とパターンを何度もマッチングさせるときに |
1605 |
|
|
最も厳しいものとなります。 |
1606 |
|
|
可能であれば $& や $'、$` を使わないようにすべきなのですが、 |
1607 |
|
|
それができないのであれば、一度これらの変数を使ってしまったら好きなように |
1608 |
|
|
使いましょう。 |
1609 |
|
|
なぜなら、罰金はすでに払ってしまったのですから。 |
1610 |
|
|
アルゴリズムの中にはこういった変数を使うことが適切であるものが |
1611 |
|
|
あるということに注意してください。 |
1612 |
|
|
リリース 5.005 からは、$& はもはや“高価な”ものではありません。 |
1613 |
|
|
|
1614 |
|
|
=begin original |
1615 |
|
|
|
1616 |
|
|
Since Perl 5.6.1 the special variables @- and @+ can functionally replace |
1617 |
|
|
$`, $& and $'. These arrays contain pointers to the beginning and end |
1618 |
|
|
of each match (see perlvar for the full story), so they give you |
1619 |
|
|
essentially the same information, but without the risk of excessive |
1620 |
|
|
string copying. |
1621 |
|
|
|
1622 |
|
|
=end original |
1623 |
|
|
|
1624 |
|
|
Perl 5.6.1 から、特殊変数 @- と @+ で $`, $&, $' の機能を |
1625 |
|
|
置き換えられるようになりました。 |
1626 |
|
|
これらの配列はそれぞれのマッチングの開始位置と終了位置へのポインタを |
1627 |
|
|
含みます(詳しい話については perlvar を参照してください)ので、 |
1628 |
|
|
本質的にはこれらから同じ情報が得られますが、 |
1629 |
|
|
過度の文字列コピーのリスクはありません。 |
1630 |
|
|
|
1631 |
|
|
=begin original |
1632 |
|
|
|
1633 |
|
|
Perl 5.10 added three specials, C<${^MATCH}>, C<${^PREMATCH}>, and |
1634 |
|
|
C<${^POSTMATCH}> to do the same job but without the global performance |
1635 |
|
|
penalty. Perl 5.10 only sets these variables if you compile or execute the |
1636 |
|
|
regular expression with the C</p> modifier. |
1637 |
|
|
|
1638 |
|
|
=end original |
1639 |
|
|
|
1640 |
|
|
Perl 5.10 では、グローバルなペナルティなしに同じ作業をするための |
1641 |
|
|
3 つの特殊変数 C<${^MATCH}>, C<${^PREMATCH}>, C<${^POSTMATCH}> が |
1642 |
|
|
追加されました。 |
1643 |
|
|
Perl 5.10 では、正規表現を C</p> 修飾子付きでコンパイルしたり |
1644 |
|
|
実行したりした場合にのみこれらの変数がセットされます。 |
1645 |
|
|
|
1646 |
|
|
=head2 What good is C<\G> in a regular expression? |
1647 |
|
|
X<\G> |
1648 |
|
|
|
1649 |
|
|
(正規表現の中で C<\G> を使うと何が良いのですか?) |
1650 |
|
|
|
1651 |
|
|
=begin original |
1652 |
|
|
|
1653 |
|
|
You use the C<\G> anchor to start the next match on the same |
1654 |
|
|
string where the last match left off. The regular |
1655 |
|
|
expression engine cannot skip over any characters to find |
1656 |
|
|
the next match with this anchor, so C<\G> is similar to the |
1657 |
|
|
beginning of string anchor, C<^>. The C<\G> anchor is typically |
1658 |
|
|
used with the C<g> flag. It uses the value of C<pos()> |
1659 |
|
|
as the position to start the next match. As the match |
1660 |
|
|
operator makes successive matches, it updates C<pos()> with the |
1661 |
|
|
position of the next character past the last match (or the |
1662 |
|
|
first character of the next match, depending on how you like |
1663 |
|
|
to look at it). Each string has its own C<pos()> value. |
1664 |
|
|
|
1665 |
|
|
=end original |
1666 |
|
|
|
1667 |
|
|
次のマッチングを同じ文字列のうち、前回のマッチングを中止したところから |
1668 |
|
|
始めるために C<\G> アンカーを使います。 |
1669 |
|
|
正規表現エンジンはこのアンカーがあるときには次のマッチングを探すために |
1670 |
|
|
何の文字も読み飛ばさないので、C<\G> は文字列先頭アンカーである C<^> と |
1671 |
|
|
似ています。 |
1672 |
|
|
C<\G> アンカーは典型的には C<g> フラグと共に使います。 |
1673 |
|
|
これは次のマッチングの開始位置として C<pos()> の値を使います。 |
1674 |
|
|
マッチング演算子がマッチングに成功すると、C<pos()> の値を最後のマッチングの |
1675 |
|
|
次の文字(または次のマッチングの最初の文字; これはあなたがこれをどのように |
1676 |
|
|
見るかの問題です)の位置に更新します。 |
1677 |
|
|
各文字列はそれぞれ独自の C<pos()> の値を持ちます。 |
1678 |
|
|
|
1679 |
|
|
=begin original |
1680 |
|
|
|
1681 |
|
|
Suppose you want to match all of consecutive pairs of digits |
1682 |
|
|
in a string like "1122a44" and stop matching when you |
1683 |
|
|
encounter non-digits. You want to match C<11> and C<22> but |
1684 |
|
|
the letter <a> shows up between C<22> and C<44> and you want |
1685 |
|
|
to stop at C<a>. Simply matching pairs of digits skips over |
1686 |
|
|
the C<a> and still matches C<44>. |
1687 |
|
|
|
1688 |
|
|
=end original |
1689 |
|
|
|
1690 |
|
|
"1122a44" のような文字列で、連続した数字のペアの全てにマッチングし、数字で |
1691 |
|
|
ないものが現れたら停止したいとします。 |
1692 |
|
|
C<11> と C<22> にはマッチングしたいですが、C<22> と C<44> の間に C<a> が |
1693 |
|
|
現れると、C<a> で停止したいとします。 |
1694 |
|
|
数字のペアのマッチングは単に C<a> を読み飛ばし、引き続き C<44> に |
1695 |
|
|
マッチングします。 |
1696 |
|
|
|
1697 |
|
|
$_ = "1122a44"; |
1698 |
|
|
my @pairs = m/(\d\d)/g; # qw( 11 22 44 ) |
1699 |
|
|
|
1700 |
|
|
=begin original |
1701 |
|
|
|
1702 |
|
|
If you use the C<\G> anchor, you force the match after C<22> to |
1703 |
|
|
start with the C<a>. The regular expression cannot match |
1704 |
|
|
there since it does not find a digit, so the next match |
1705 |
|
|
fails and the match operator returns the pairs it already |
1706 |
|
|
found. |
1707 |
|
|
|
1708 |
|
|
=end original |
1709 |
|
|
|
1710 |
|
|
C<\G> アンカーを使うと、C<22> の後のマッチングを C<a> から始めることを |
1711 |
|
|
強制します。 |
1712 |
|
|
ここでは数字が見付からないのでマッチングできず、従って次のマッチングは |
1713 |
|
|
失敗してマッチング演算子は既に見付かったペアを返します。 |
1714 |
|
|
|
1715 |
|
|
$_ = "1122a44"; |
1716 |
|
|
my @pairs = m/\G(\d\d)/g; # qw( 11 22 ) |
1717 |
|
|
|
1718 |
|
|
=begin original |
1719 |
|
|
|
1720 |
|
|
You can also use the C<\G> anchor in scalar context. You |
1721 |
|
|
still need the C<g> flag. |
1722 |
|
|
|
1723 |
|
|
=end original |
1724 |
|
|
|
1725 |
|
|
スカラコンテキストにも C<\G> アンカーが使えます。 |
1726 |
|
|
C<g> フラグはまだ必要です。 |
1727 |
|
|
|
1728 |
|
|
$_ = "1122a44"; |
1729 |
|
|
while( m/\G(\d\d)/g ) { |
1730 |
|
|
print "Found $1\n"; |
1731 |
|
|
} |
1732 |
|
|
|
1733 |
|
|
=begin original |
1734 |
|
|
|
1735 |
|
|
After the match fails at the letter C<a>, perl resets C<pos()> |
1736 |
|
|
and the next match on the same string starts at the beginning. |
1737 |
|
|
|
1738 |
|
|
=end original |
1739 |
|
|
|
1740 |
|
|
文字 C<a> のマッチングに失敗した後、perl は C<pos()> をリセットし、 |
1741 |
|
|
同じ文字列に対する次のマッチングは先頭から行います。 |
1742 |
|
|
|
1743 |
|
|
$_ = "1122a44"; |
1744 |
|
|
while( m/\G(\d\d)/g ) { |
1745 |
|
|
print "Found $1\n"; |
1746 |
|
|
} |
1747 |
|
|
|
1748 |
|
|
print "Found $1 after while" if m/(\d\d)/g; # finds "11" |
1749 |
|
|
|
1750 |
|
|
=begin original |
1751 |
|
|
|
1752 |
|
|
You can disable C<pos()> resets on fail with the C<c> flag, documented |
1753 |
|
|
in L<perlop> and L<perlreref>. Subsequent matches start where the last |
1754 |
|
|
successful match ended (the value of C<pos()>) even if a match on the |
1755 |
|
|
same string has failed in the meantime. In this case, the match after |
1756 |
|
|
the C<while()> loop starts at the C<a> (where the last match stopped), |
1757 |
|
|
and since it does not use any anchor it can skip over the C<a> to find |
1758 |
|
|
C<44>. |
1759 |
|
|
|
1760 |
|
|
=end original |
1761 |
|
|
|
1762 |
|
|
L<perlop> と L<perlreref> に書いているように、C<c> フラグをつけることで |
1763 |
|
|
C<pos()> のリセットを抑制できます。 |
1764 |
|
|
引き続くマッチングは、その間に同じ文字列でのマッチングが失敗していても、 |
1765 |
|
|
直前の成功したマッチングが終了した場所 (C<pos()> の値) から開始されます。 |
1766 |
|
|
この場合、C<while()> ループの後のマッチングは (最後のマッチングが停止した) |
1767 |
|
|
C<a> から開始され、何のアンカーも使っていないので、C<44> を見つけるために |
1768 |
|
|
C<a> をスキップできます。 |
1769 |
|
|
|
1770 |
|
|
$_ = "1122a44"; |
1771 |
|
|
while( m/\G(\d\d)/gc ) { |
1772 |
|
|
print "Found $1\n"; |
1773 |
|
|
} |
1774 |
|
|
|
1775 |
|
|
print "Found $1 after while" if m/(\d\d)/g; # finds "44" |
1776 |
|
|
|
1777 |
|
|
=begin original |
1778 |
|
|
|
1779 |
|
|
Typically you use the C<\G> anchor with the C<c> flag |
1780 |
|
|
when you want to try a different match if one fails, |
1781 |
|
|
such as in a tokenizer. Jeffrey Friedl offers this example |
1782 |
|
|
which works in 5.004 or later. |
1783 |
|
|
|
1784 |
|
|
=end original |
1785 |
|
|
|
1786 |
|
|
典型的には、トークナイザのようなものの中で、一つのマッチングに失敗した |
1787 |
|
|
ときに他のマッチングを試したいときに、C<\G> アンカーに C<c> フラグを |
1788 |
|
|
つけて使います。 |
1789 |
|
|
Jeffrey Friedl が、5.004 以降で動作する、これに関する例を提供してくれました。 |
1790 |
|
|
|
1791 |
|
|
while (<>) { |
1792 |
|
|
chomp; |
1793 |
|
|
PARSER: { |
1794 |
|
|
m/ \G( \d+\b )/gcx && do { print "number: $1\n"; redo; }; |
1795 |
|
|
m/ \G( \w+ )/gcx && do { print "word: $1\n"; redo; }; |
1796 |
|
|
m/ \G( \s+ )/gcx && do { print "space: $1\n"; redo; }; |
1797 |
|
|
m/ \G( [^\w\d]+ )/gcx && do { print "other: $1\n"; redo; }; |
1798 |
|
|
} |
1799 |
|
|
} |
1800 |
|
|
|
1801 |
|
|
=begin original |
1802 |
|
|
|
1803 |
|
|
For each line, the C<PARSER> loop first tries to match a series |
1804 |
|
|
of digits followed by a word boundary. This match has to |
1805 |
|
|
start at the place the last match left off (or the beginning |
1806 |
|
|
of the string on the first match). Since C<m/ \G( \d+\b |
1807 |
|
|
)/gcx> uses the C<c> flag, if the string does not match that |
1808 |
|
|
regular expression, perl does not reset pos() and the next |
1809 |
|
|
match starts at the same position to try a different |
1810 |
|
|
pattern. |
1811 |
|
|
|
1812 |
|
|
=end original |
1813 |
|
|
|
1814 |
|
|
それぞれの行において、C<PARSER> ループはまず数字の列に引き続く単語境界に |
1815 |
|
|
マッチングしようと試みます。 |
1816 |
|
|
このマッチングは直前のマッチングが行われた場所(最初のマッチングの場合は |
1817 |
|
|
文字列の先頭)から始められなければなりません。 |
1818 |
|
|
C<m/ \G( \d+\b )/gcx> は C<c> フラグを使っているので、もし文字列がこの |
1819 |
|
|
正規表現にマッチングしなければ、perl は pos() をリセットせず、次の |
1820 |
|
|
マッチングは、他のパターンを試す場合でも同じ位置から開始します。 |
1821 |
|
|
|
1822 |
|
|
=head2 Are Perl regexes DFAs or NFAs? Are they POSIX compliant? |
1823 |
|
|
X<DFA> X<NFA> X<POSIX> |
1824 |
|
|
|
1825 |
|
|
(Perl の正規表現ルーチンは DFA ですか NFA ですか? また、それは POSIX に従ってますか?) |
1826 |
|
|
|
1827 |
|
|
=begin original |
1828 |
|
|
|
1829 |
|
|
While it's true that Perl's regular expressions resemble the DFAs |
1830 |
|
|
(deterministic finite automata) of the egrep(1) program, they are in |
1831 |
|
|
fact implemented as NFAs (non-deterministic finite automata) to allow |
1832 |
|
|
backtracking and backreferencing. And they aren't POSIX-style either, |
1833 |
|
|
because those guarantee worst-case behavior for all cases. (It seems |
1834 |
|
|
that some people prefer guarantees of consistency, even when what's |
1835 |
|
|
guaranteed is slowness.) See the book "Mastering Regular Expressions" |
1836 |
|
|
(from O'Reilly) by Jeffrey Friedl for all the details you could ever |
1837 |
|
|
hope to know on these matters (a full citation appears in |
1838 |
|
|
L<perlfaq2>). |
1839 |
|
|
|
1840 |
|
|
=end original |
1841 |
|
|
|
1842 |
|
|
Perl の正規表現は egrep(1) の DFA (deterministic finite automata, |
1843 |
|
|
決定性有限オートマトン)と似たものではあるのですが、 |
1844 |
|
|
実際のところはバックトラックや後方参照 (backreferencing)のために |
1845 |
|
|
NFA として実装されています。 |
1846 |
|
|
そして、Perl の正規表現は POSIX 形式のものでもありません。 |
1847 |
|
|
なぜなら、それはすべてのケースにおいて最悪の振る舞いを行うからです |
1848 |
|
|
(一部の人は、それが遅さをもたらすにもかからわず、一貫性をもたらすという点を |
1849 |
|
|
好んでいるようです)。 |
1850 |
|
|
上記のことなどに関しての詳細は Jeffrery Friedl による O'Reilly から |
1851 |
|
|
出版されている "Mastering Regular Expressions" という本を参照してください。 |
1852 |
|
|
|
1853 |
|
|
=head2 What's wrong with using grep in a void context? |
1854 |
|
|
X<grep> |
1855 |
|
|
|
1856 |
|
|
(無効コンテキストで grep を使うことのどこが間違っているのでしょうか?) |
1857 |
|
|
|
1858 |
|
|
=begin original |
1859 |
|
|
|
1860 |
|
|
The problem is that grep builds a return list, regardless of the context. |
1861 |
|
|
This means you're making Perl go to the trouble of building a list that |
1862 |
|
|
you then just throw away. If the list is large, you waste both time and space. |
1863 |
|
|
If your intent is to iterate over the list, then use a for loop for this |
1864 |
|
|
purpose. |
1865 |
|
|
|
1866 |
|
|
=end original |
1867 |
|
|
|
1868 |
|
|
問題は、grep はそのコンテキストには関係なくリストを返すことです。 |
1869 |
|
|
これはつまり、Perl にあなたが無視してしまうための戻り値のリストを |
1870 |
|
|
作らせるということです。 |
1871 |
|
|
もしリストが大きいなら、時間とメモリの両方を無駄にします。 |
1872 |
|
|
あなたの目的がリスト全体に対して反復することなら、for ループを |
1873 |
|
|
使ってください。 |
1874 |
|
|
|
1875 |
|
|
=begin original |
1876 |
|
|
|
1877 |
|
|
In perls older than 5.8.1, map suffers from this problem as well. |
1878 |
|
|
But since 5.8.1, this has been fixed, and map is context aware - in void |
1879 |
|
|
context, no lists are constructed. |
1880 |
|
|
|
1881 |
|
|
=end original |
1882 |
|
|
|
1883 |
|
|
5.8.1 より前の perl では、map も同じ問題の影響を受けていました。 |
1884 |
|
|
しかし 5.8.1 から、これは修正され、map はコンテキストを |
1885 |
|
|
認識するようになりました - 無効コンテキストではリストは作られません。 |
1886 |
|
|
|
1887 |
|
|
=head2 How can I match strings with multibyte characters? |
1888 |
|
|
X<regex, and multibyte characters> X<regexp, and multibyte characters> |
1889 |
|
|
X<regular expression, and multibyte characters> X<martian> X<encoding, Martian> |
1890 |
|
|
|
1891 |
|
|
(マルチバイト文字を含む文字列をマッチングさせるには?) |
1892 |
|
|
|
1893 |
|
|
=begin original |
1894 |
|
|
|
1895 |
|
|
Starting from Perl 5.6 Perl has had some level of multibyte character |
1896 |
|
|
support. Perl 5.8 or later is recommended. Supported multibyte |
1897 |
|
|
character repertoires include Unicode, and legacy encodings |
1898 |
|
|
through the Encode module. See L<perluniintro>, L<perlunicode>, |
1899 |
|
|
and L<Encode>. |
1900 |
|
|
|
1901 |
|
|
=end original |
1902 |
|
|
|
1903 |
|
|
Perl 5.6 から、Perl にはあるレベルのマルチバイト文字サポートがあります。 |
1904 |
|
|
Perl 5.8 以降を推奨します。 |
1905 |
|
|
対応するマルチバイト文字のレパートリーには、Unicode と、Encode モジュール |
1906 |
|
|
経由のレガシーエンコーディングを含みます。 |
1907 |
|
|
L<perluniintro>, L<perlunicode>, L<Encode> を参照してください。 |
1908 |
|
|
|
1909 |
|
|
=begin original |
1910 |
|
|
|
1911 |
|
|
If you are stuck with older Perls, you can do Unicode with the |
1912 |
|
|
L<Unicode::String> module, and character conversions using the |
1913 |
|
|
L<Unicode::Map8> and L<Unicode::Map> modules. If you are using |
1914 |
|
|
Japanese encodings, you might try using the jperl 5.005_03. |
1915 |
|
|
|
1916 |
|
|
=end original |
1917 |
|
|
|
1918 |
|
|
もしもっと古い Perl に捕まっているなら、L<Unicode::String> モジュールで |
1919 |
|
|
Unicode ができ、L<Unicode::Map8> と L<Unicode::Map> のモジュールを使って |
1920 |
|
|
文字変換ができます。 |
1921 |
|
|
日本語エンコーディングを使っているなら、jperl 5.005_03 を使ってみたいかも |
1922 |
|
|
しれません。 |
1923 |
|
|
|
1924 |
|
|
=begin original |
1925 |
|
|
|
1926 |
|
|
Finally, the following set of approaches was offered by Jeffrey |
1927 |
|
|
Friedl, whose article in issue #5 of The Perl Journal talks about |
1928 |
|
|
this very matter. |
1929 |
|
|
|
1930 |
|
|
=end original |
1931 |
|
|
|
1932 |
|
|
最後に、The Perl Journal の第五号でこの問題についてより詳しい記事を書いた |
1933 |
|
|
Jeffery Friedl により提案された手法の幾つかを挙げます。 |
1934 |
|
|
|
1935 |
|
|
=begin original |
1936 |
|
|
|
1937 |
|
|
Let's suppose you have some weird Martian encoding where pairs of |
1938 |
|
|
ASCII uppercase letters encode single Martian letters (i.e. the two |
1939 |
|
|
bytes "CV" make a single Martian letter, as do the two bytes "SG", |
1940 |
|
|
"VS", "XX", etc.). Other bytes represent single characters, just like |
1941 |
|
|
ASCII. |
1942 |
|
|
|
1943 |
|
|
=end original |
1944 |
|
|
|
1945 |
|
|
さて、ここで ASCII の大文字二文字で火星語の符号化をしていると仮定しましょう |
1946 |
|
|
(たとえば、"CV", "SG", "VS", "XX" などといった二バイトの並びが |
1947 |
|
|
火星語の一文字を表わすということです)。 |
1948 |
|
|
|
1949 |
|
|
=begin original |
1950 |
|
|
|
1951 |
|
|
So, the string of Martian "I am CVSGXX!" uses 12 bytes to encode the |
1952 |
|
|
nine characters 'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!'. |
1953 |
|
|
|
1954 |
|
|
=end original |
1955 |
|
|
|
1956 |
|
|
ですから、火星語の符号化をしている 12 バイトの "I am CVSGXX!" 文字列は、 |
1957 |
|
|
'I', ' ', 'a', 'm', ' ', 'CV', 'SG', 'XX', '!' という九文字で構成されます。 |
1958 |
|
|
|
1959 |
|
|
=begin original |
1960 |
|
|
|
1961 |
|
|
Now, say you want to search for the single character C</GX/>. Perl |
1962 |
|
|
doesn't know about Martian, so it'll find the two bytes "GX" in the "I |
1963 |
|
|
am CVSGXX!" string, even though that character isn't there: it just |
1964 |
|
|
looks like it is because "SG" is next to "XX", but there's no real |
1965 |
|
|
"GX". This is a big problem. |
1966 |
|
|
|
1967 |
|
|
=end original |
1968 |
|
|
|
1969 |
|
|
ここで、C</GX/> という一文字検索をしたいと考えてみましょう。 |
1970 |
|
|
Perl は火星語については何も知りませんから、"I am CVSGXX!" という文字列にある |
1971 |
|
|
"GX" 二バイトを見つけ出してしまうでしょうが、これは文字として |
1972 |
|
|
そこにあるものではありません。 |
1973 |
|
|
つまり、"SG" に続けて "XX" があるのでそう見えるだけであって、 |
1974 |
|
|
本当に "GX" があるわけではないのです。 |
1975 |
|
|
これは大きな問題です。 |
1976 |
|
|
|
1977 |
|
|
=begin original |
1978 |
|
|
|
1979 |
|
|
Here are a few ways, all painful, to deal with it: |
1980 |
|
|
|
1981 |
|
|
=end original |
1982 |
|
|
|
1983 |
|
|
この問題に対処する方法が、どれもうんざりするようなものですが、幾つかあります: |
1984 |
|
|
|
1985 |
|
|
# Make sure adjacent "martian" bytes are no longer adjacent. |
1986 |
|
|
$martian =~ s/([A-Z][A-Z])/ $1 /g; |
1987 |
|
|
|
1988 |
|
|
print "found GX!\n" if $martian =~ /GX/; |
1989 |
|
|
|
1990 |
|
|
=begin original |
1991 |
|
|
|
1992 |
|
|
Or like this: |
1993 |
|
|
|
1994 |
|
|
=end original |
1995 |
|
|
|
1996 |
|
|
あるいは: |
1997 |
|
|
|
1998 |
|
|
my @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g; |
1999 |
|
|
# above is conceptually similar to: my @chars = $text =~ m/(.)/g; |
2000 |
|
|
# |
2001 |
|
|
foreach my $char (@chars) { |
2002 |
|
|
print "found GX!\n", last if $char eq 'GX'; |
2003 |
|
|
} |
2004 |
|
|
|
2005 |
|
|
=begin original |
2006 |
|
|
|
2007 |
|
|
Or like this: |
2008 |
|
|
|
2009 |
|
|
=end original |
2010 |
|
|
|
2011 |
|
|
あるいは: |
2012 |
|
|
|
2013 |
|
|
while ($martian =~ m/\G([A-Z][A-Z]|.)/gs) { # \G probably unneeded |
2014 |
|
|
if ($1 eq 'GX') { |
2015 |
|
|
print "found GX!\n"; |
2016 |
|
|
last; |
2017 |
|
|
} |
2018 |
|
|
} |
2019 |
|
|
|
2020 |
|
|
=begin original |
2021 |
|
|
|
2022 |
|
|
Here's another, slightly less painful, way to do it from Benjamin |
2023 |
|
|
Goldberg, who uses a zero-width negative look-behind assertion. |
2024 |
|
|
|
2025 |
|
|
=end original |
2026 |
|
|
|
2027 |
|
|
以下は Benjamin Goldberg による、同じことをもう少しましに行うもので、 |
2028 |
|
|
ゼロ幅否定前方参照アサーションを使っています。 |
2029 |
|
|
|
2030 |
|
|
print "found GX!\n" if $martian =~ m/ |
2031 |
|
|
(?<![A-Z]) |
2032 |
|
|
(?:[A-Z][A-Z])*? |
2033 |
|
|
GX |
2034 |
|
|
/x; |
2035 |
|
|
|
2036 |
|
|
=begin original |
2037 |
|
|
|
2038 |
|
|
This succeeds if the "martian" character GX is in the string, and fails |
2039 |
|
|
otherwise. If you don't like using (?<!), a zero-width negative |
2040 |
|
|
look-behind assertion, you can replace (?<![A-Z]) with (?:^|[^A-Z]). |
2041 |
|
|
|
2042 |
|
|
=end original |
2043 |
|
|
|
2044 |
|
|
これはもし "martian" 文字 GX が文字列にあれば成功し、そうでなければ |
2045 |
|
|
失敗します。 |
2046 |
|
|
ゼロ幅否定前方参照アサーション (?<!) を使いたくないなら、(?<![A-Z]) を |
2047 |
|
|
(?:^|[^A-Z]) で置き換えられます。 |
2048 |
|
|
|
2049 |
|
|
=begin original |
2050 |
|
|
|
2051 |
|
|
It does have the drawback of putting the wrong thing in $-[0] and $+[0], |
2052 |
|
|
but this usually can be worked around. |
2053 |
|
|
|
2054 |
|
|
=end original |
2055 |
|
|
|
2056 |
|
|
これには $-[0] と $+[0] に間違ったものが入るという欠点がありますが、普通 |
2057 |
|
|
これは回避できます。 |
2058 |
|
|
|
2059 |
|
|
=head2 How do I match a regular expression that's in a variable? |
2060 |
|
|
X<regex, in variable> X<eval> X<regex> X<quotemeta> X<\Q, regex> |
2061 |
|
|
X<\E, regex> X<qr//> |
2062 |
|
|
|
2063 |
|
|
(変数に入っている正規表現でマッチングを行うには?) |
2064 |
|
|
|
2065 |
|
|
=begin original |
2066 |
|
|
|
2067 |
|
|
(contributed by brian d foy) |
2068 |
|
|
|
2069 |
|
|
=end original |
2070 |
|
|
|
2071 |
|
|
(brian d foy によって寄贈されました) |
2072 |
|
|
|
2073 |
|
|
=begin original |
2074 |
|
|
|
2075 |
|
|
We don't have to hard-code patterns into the match operator (or |
2076 |
|
|
anything else that works with regular expressions). We can put the |
2077 |
|
|
pattern in a variable for later use. |
2078 |
|
|
|
2079 |
|
|
=end original |
2080 |
|
|
|
2081 |
|
|
マッチング演算子(あるいはその他の正規表現として働くもの)にパターンを |
2082 |
|
|
ハードコーディングする必要はありません。 |
2083 |
|
|
後で使うためにパターンを変数に入れることができます。 |
2084 |
|
|
|
2085 |
|
|
=begin original |
2086 |
|
|
|
2087 |
|
|
The match operator is a double quote context, so you can interpolate |
2088 |
|
|
your variable just like a double quoted string. In this case, you |
2089 |
|
|
read the regular expression as user input and store it in C<$regex>. |
2090 |
|
|
Once you have the pattern in C<$regex>, you use that variable in the |
2091 |
|
|
match operator. |
2092 |
|
|
|
2093 |
|
|
=end original |
2094 |
|
|
|
2095 |
|
|
マッチング演算子はダブルクォートコンテキストなので、ダブルクォート文字列と |
2096 |
|
|
同様に変数展開できます。 |
2097 |
|
|
個の場合、正規表現をユーザー入力として読み込んで、C<$regex> に保管します。 |
2098 |
|
|
パターンが C<$regex> に入れば、この変数をマッチング演算子の中で使えます。 |
2099 |
|
|
|
2100 |
|
|
chomp( my $regex = <STDIN> ); |
2101 |
|
|
|
2102 |
|
|
if( $string =~ m/$regex/ ) { ... } |
2103 |
|
|
|
2104 |
|
|
=begin original |
2105 |
|
|
|
2106 |
|
|
Any regular expression special characters in C<$regex> are still |
2107 |
|
|
special, and the pattern still has to be valid or Perl will complain. |
2108 |
|
|
For instance, in this pattern there is an unpaired parenthesis. |
2109 |
|
|
|
2110 |
|
|
=end original |
2111 |
|
|
|
2112 |
|
|
C<$regex> 内の全ての正規表現特殊文字は特殊なままで、パターンが |
2113 |
|
|
有効でなければ Perl はエラーを出します。 |
2114 |
|
|
例えば、このパターンには組になっていないかっこがあります。 |
2115 |
|
|
|
2116 |
|
|
my $regex = "Unmatched ( paren"; |
2117 |
|
|
|
2118 |
|
|
"Two parens to bind them all" =~ m/$regex/; |
2119 |
|
|
|
2120 |
|
|
=begin original |
2121 |
|
|
|
2122 |
|
|
When Perl compiles the regular expression, it treats the parenthesis |
2123 |
|
|
as the start of a memory match. When it doesn't find the closing |
2124 |
|
|
parenthesis, it complains: |
2125 |
|
|
|
2126 |
|
|
=end original |
2127 |
|
|
|
2128 |
|
|
Perl が正規表現をコンパイルする時に、かっこをマッチング記憶の開始として |
2129 |
|
|
扱います。 |
2130 |
|
|
閉じかっこが見つからないと、エラーが出ます: |
2131 |
|
|
|
2132 |
|
|
Unmatched ( in regex; marked by <-- HERE in m/Unmatched ( <-- HERE paren/ at script line 3. |
2133 |
|
|
|
2134 |
|
|
=begin original |
2135 |
|
|
|
2136 |
|
|
You can get around this in several ways depending on our situation. |
2137 |
|
|
First, if you don't want any of the characters in the string to be |
2138 |
|
|
special, you can escape them with C<quotemeta> before you use the string. |
2139 |
|
|
|
2140 |
|
|
=end original |
2141 |
|
|
|
2142 |
|
|
状況に依存して、いくつかの方法でこれを回避できます。 |
2143 |
|
|
まず、文字列中のどの文字も特別ではないなら、文字列を使う前に |
2144 |
|
|
C<quotemeta> でエスケープできます。 |
2145 |
|
|
|
2146 |
|
|
chomp( my $regex = <STDIN> ); |
2147 |
|
|
$regex = quotemeta( $regex ); |
2148 |
|
|
|
2149 |
|
|
if( $string =~ m/$regex/ ) { ... } |
2150 |
|
|
|
2151 |
|
|
=begin original |
2152 |
|
|
|
2153 |
|
|
You can also do this directly in the match operator using the C<\Q> |
2154 |
|
|
and C<\E> sequences. The C<\Q> tells Perl where to start escaping |
2155 |
|
|
special characters, and the C<\E> tells it where to stop (see L<perlop> |
2156 |
|
|
for more details). |
2157 |
|
|
|
2158 |
|
|
=end original |
2159 |
|
|
|
2160 |
|
|
C<\Q> と C<\E> のシーケンスを使うことで、これをマッチング演算子の中で直接 |
2161 |
|
|
行うこともできます。 |
2162 |
|
|
C<\Q> は Perl に特殊文字のエスケープを開始する位置を示し、C<\E> はそれを |
2163 |
|
|
終了する位置を示します (さらなる詳細については L<perlop> を |
2164 |
|
|
参照してください)。 |
2165 |
|
|
|
2166 |
|
|
chomp( my $regex = <STDIN> ); |
2167 |
|
|
|
2168 |
|
|
if( $string =~ m/\Q$regex\E/ ) { ... } |
2169 |
|
|
|
2170 |
|
|
=begin original |
2171 |
|
|
|
2172 |
|
|
Alternately, you can use C<qr//>, the regular expression quote operator (see |
2173 |
|
|
L<perlop> for more details). It quotes and perhaps compiles the pattern, |
2174 |
|
|
and you can apply regular expression flags to the pattern. |
2175 |
|
|
|
2176 |
|
|
=end original |
2177 |
|
|
|
2178 |
|
|
あるいは、正規表現クォート演算子である C<qr//> が使えます(さらなる |
2179 |
|
|
詳細については L<perlop> を参照してください)。 |
2180 |
|
|
これはパターンをクォートし、おそらくはコンパイルされます; |
2181 |
|
|
また、パターンに正規表現フラグを適用できます。 |
2182 |
|
|
|
2183 |
|
|
chomp( my $input = <STDIN> ); |
2184 |
|
|
|
2185 |
|
|
my $regex = qr/$input/is; |
2186 |
|
|
|
2187 |
|
|
$string =~ m/$regex/ # same as m/$input/is; |
2188 |
|
|
|
2189 |
|
|
=begin original |
2190 |
|
|
|
2191 |
|
|
You might also want to trap any errors by wrapping an C<eval> block |
2192 |
|
|
around the whole thing. |
2193 |
|
|
|
2194 |
|
|
=end original |
2195 |
|
|
|
2196 |
|
|
全体を C<eval> ブロックで包むことで全てのエラーをトラップしたいかも |
2197 |
|
|
しれません。 |
2198 |
|
|
|
2199 |
|
|
chomp( my $input = <STDIN> ); |
2200 |
|
|
|
2201 |
|
|
eval { |
2202 |
|
|
if( $string =~ m/\Q$input\E/ ) { ... } |
2203 |
|
|
}; |
2204 |
|
|
warn $@ if $@; |
2205 |
|
|
|
2206 |
|
|
=begin original |
2207 |
|
|
|
2208 |
|
|
Or... |
2209 |
|
|
|
2210 |
|
|
=end original |
2211 |
|
|
|
2212 |
|
|
または... |
2213 |
|
|
|
2214 |
|
|
my $regex = eval { qr/$input/is }; |
2215 |
|
|
if( defined $regex ) { |
2216 |
|
|
$string =~ m/$regex/; |
2217 |
|
|
} |
2218 |
|
|
else { |
2219 |
|
|
warn $@; |
2220 |
|
|
} |
2221 |
|
|
|
2222 |
|
|
=head1 AUTHOR AND COPYRIGHT |
2223 |
|
|
|
2224 |
|
|
Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and |
2225 |
|
|
other authors as noted. All rights reserved. |
2226 |
|
|
|
2227 |
|
|
This documentation is free; you can redistribute it and/or modify it |
2228 |
|
|
under the same terms as Perl itself. |
2229 |
|
|
|
2230 |
|
|
Irrespective of its distribution, all code examples in this file |
2231 |
|
|
are hereby placed into the public domain. You are permitted and |
2232 |
|
|
encouraged to use this code in your own programs for fun |
2233 |
|
|
or for profit as you see fit. A simple comment in the code giving |
2234 |
|
|
credit would be courteous but is not required. |
2235 |
|
|
|
2236 |
|
|
=begin meta |
2237 |
|
|
|
2238 |
|
|
Translate: 吉村 寿人 <JAE00534@niftyserve.or.jp> |
2239 |
|
|
Update: SHIRAKATA Kentaro <argrath@ub32.org> (5.6.1-) |
2240 |
|
|
Status: in progress |
2241 |
|
|
|
2242 |
|
|
=end meta |
2243 |
|
|
|