gpt4 book ai didi

正则表达式 - 如何提取两个不同字符串之间的字符串?

转载 作者:行者123 更新时间:2023-12-02 08:49:40 24 4
gpt4 key购买 nike

给定以下行:

rebeka mecsek:/export/home5/users/rebeka;

I'd like to get only the word "mecsek" from the line.There is a space between the word "rebeka" and "mecsek", and the line beginning with no space.

I tried the following:

$homeserver=~s/.*\s//;

但我不想要冒号或它后面的部分,只想要“mecsek”这个词。

谁能帮帮我?

非常感谢!

最佳答案

记住Randal’s rule :

Randal Schwartz (author of Learning Perl) says:

Use capturing or m//g when you know what you want to keep.
Use split when you know what you want to throw away.

你知道你想保留什么,但你并没有告诉我们你所知道的一切。您是否希望在该行的第一个空格之后连续运行单词字符?

print $1, "\n" if $homeserver =~ / (\w+)/;

是否要在 :/ 之前保留最长、最左边的单词字符字符串,无论它在哪里?

print $1, "\n" if $homeserver =~ /(\w+):\//;

我们可以相信 rebeka 位于字符串的开头吗?

print $1, "\n" if $homeserver =~ /^rebeka (\w+)/;

如果不是,是否可以安全地假设字符串的开头是一些连续的单词字符?

print $1, "\n" if $homeserver =~ /^\w+ (\w+)/;

当与正则表达式匹配时,定义 anchor :您可以依赖的特征出现在文本中,作为您想要保留的内容的标记或书挡。另请注意,上述示例仅在条件内使用 $1;永远不要无条件地使用捕获变量。

关于正则表达式 - 如何提取两个不同字符串之间的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9393506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com