[英]Find a word which is after a pattern and before another pattern using perl
I want to find a word in a file which is after a particular pattern and before a particular pattern. 我想在文件中的某个特定模式之后和某个特定模式之前找到一个单词。 Here is the content from the file: 这是文件中的内容:
print("Hi", "My name is", "Tej");
So, I want to get the word Tej
alone and store it into an array. 因此,我想单独使用Tej
一词并将其存储到数组中。 Similarly, I have many such files with similar pattern as above but with different names, so I want to push all those names into an array. 同样,我有许多这样的文件,它们的样式与上面相似,但名称不同,因此我想将所有这些名称都放入一个数组中。 ie I want the words from the from the files which are after the pattern print("Hi", "My name is", "
and before the pattern ");
即我要从模式print("Hi", "My name is", "
后的文件中的单词print("Hi", "My name is", "
和模式");
之前");
. 。
Sometimes, the space after the commas are missing. 有时,逗号后的空格会丢失。
I wrote the script for opening files and passing the file handle to a function to search for the word which is after and before the pattern. 我编写了用于打开文件并将文件句柄传递给函数的脚本,以搜索模式之后和之前的单词。 The code for the function is as follows: 该函数的代码如下:
sub search{
my $file_handle = shift;
while (<$file_handle>)
{
/.print("Hi", "My name is", "[\s]+([A-Za-z_0-9]+)/ ;
push @array, $1;
}
}
I know the regex doesn't work but I am not sure about how to find the word I need. 我知道正则表达式不起作用,但是我不确定如何找到需要的单词。 Any help provided is appreciated. 任何提供的帮助表示赞赏。 Thanks 谢谢
Here's how I would do it: 这是我的处理方式:
sub search {
my $file_handle = shift;
while (<$file_handle>) {
if (/print\("Hi", ?"My name is", ?"([^"]+)"\);/) {
push @array, $1;
}
}
}
I escaped the special characters inside the regex (ie (
and )
in this case), and I used "([^"]+)"
to match all the non quotes inside the quotes. 我转义了正则表达式内的特殊字符(即本例中的(
和)
),并使用"([^"]+)"
来匹配引号内的所有非引号。
The question mark after the space makes the presence of the space optional. 空格后的问号使空格的出现是可选的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.