【发布时间】:2014-03-09 06:38:22
【问题描述】:
我正在尝试在 perl 中进行模式匹配,在其中我检查从文件中读取的行的开头是否存在“非空白字符”,并返回第一个匹配的单词。
问题是,有时我的单词会以':'结尾,有时我不会。
例如:
假设我有一个包含以下内容的文件。有时带有替代内容。该文件会自动填充。
some0 Loren Posem:is some color::and some foo bar with 1023:4632
some more content added to the file
some3 Loren Posem:is some color::and some foo bar with 1023:4632
some more content added to the file
替代内容:
some1: Loren Posem:is some will be different with some number 5423:32
some more content added to the file
some3: Loren Posem:is some will be different with some number 5423:32
some more content added to the file
现在我只想从这个文件中提取第一个单词。但是如果文件有替代内容,我仍然只想要第一个单词忽略尾随的':'。
我这里只需要模式匹配部分。 这是我到目前为止所得到的。
foreach ...
if (/^(\S+):/) {
print $1;
}
/* 如果我使用上述模式匹配,我将从替代内容中获取第一个单词,即 some1 和 some3 忽略尾随的“:”但是当我有原始内容时,$1 不匹配。 */
但是如果我使用
foreach ...
if (/^(\S+)/) {
print $1;
}
/* 现在替代内容将不匹配。 */
这里有什么提示吗?
【问题讨论】:
标签: regex perl pattern-matching