I am trying to use RegEx within my Perl script to parse a file to match: Space and \n
(newline) in an alternating manner:
First I would like it to match space then a \n
, then a spac开发者_高级运维e (which is on a new line in the file... and so on).
You can do:
if($file =~/ |(?: \n)+ ?/) {
print $file." has the pattern\n";
}
The regex used is |(?: \n)+ ?
which matches:
- Single space or
- One or more
space\n
followed by an optionalspace
Try this:
(^ \n)+
You said you wanted the second space in your pattern to be on the new line. Now whether you'll be able to get this depends on where you got your string from (well, maybe not where, but I guess you get my point). If the data you're parsing is read from a file, then you must read the file in paragraph mode (i.e. each paragraph instead of each line will constitute a record).
Assuming you are using the file handle FILE, do this:
{
local $/ = ""; # one paragraph constitutes one record
while (<FILE>) {
if (/ \n /) {
print "Found one match!\n";
}
}
}
Please note that the regex pattern I have used does not take into account multiple occurrences of space-newline-space, as I wasn't sure what exactly you were trying to do. But anyway, my main point is the use of
local $/ = "";
HTH
To match the Start of a line, use caret ^
.
To match the space, you can use a literal space, or for any whitespace, use \s
.
Putting sgm
at the end of the pattern, e.g. /pattern/sgm
will cause it to match across lines.
There is more info and some examples at perldoc perlfaq6 if you are interested.
精彩评论