Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何获取给定字符串的子字符串,直到指定字符第一次出现?_String_Perl_Substring - Fatal编程技术网

String 如何获取给定字符串的子字符串,直到指定字符第一次出现?

String 如何获取给定字符串的子字符串,直到指定字符第一次出现?,string,perl,substring,String,Perl,Substring,问题是perl 例如,如果我有“hello.world”,并且指定的字符是。那么我想要的结果是“hello”请参见: 使用: 或使用regexp: my ($substring2) = $string =~ /(.*)?\./; 为您提供了另一种可能性: my $string = 'hello.world'; print ((split /\./, $string)[0], "\n"); 本着TIMTOWTDI的精神,并引入新功能:使用/r my $partial = $string =~

问题是perl

例如,如果我有
“hello.world”
,并且指定的字符是
那么我想要的结果是
“hello”

请参见:

使用:

或使用regexp:

my ($substring2) = $string =~ /(.*)?\./;
为您提供了另一种可能性:

my $string = 'hello.world';
print ((split /\./, $string)[0], "\n");

本着TIMTOWTDI的精神,并引入新功能:使用
/r

my $partial = $string =~ s/\..*//sr;
贪婪的
*
结尾将切掉第一个句点之后的所有内容,包括可能的换行符(
/s
选项),但保留原始字符串不变,并且不需要paren强制列表上下文(
/r
选项)

引自perlop:

如果使用/r(非破坏性)选项,则它将运行 替换字符串的副本,而不是返回 替换数,它返回副本是否为 替代发生了。启用/r时,不会更改原始字符串 用过。副本将始终是一个普通字符串,即使输入是 对象或绑定变量


我并不是说perldoc引用是一个“RTFM”,而是一个“有关更多信息,请参阅:____;:)substr将给出字符串直到第一个句点
,正则表达式将给出字符串直到最后一个句点。注意区别。对非贪婪正则表达式使用
*?
可以获得相同的功能;my$world=substr($string,$dot,length($string));
use strict;
use warnings;

my $string = "hello.world";
my $dot = index($string, '.');
my $word = substr($string, 0, $dot);

print "$word\n";
my $string = 'hello.world';
print ((split /\./, $string)[0], "\n");
my $partial = $string =~ s/\..*//sr;