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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8256382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:18:08  来源:igfitidea点击:

How to take substring of a given string until the first appearance of specified character?

stringperlsubstring

提问by Mihran Hovsepyan

The question is for perl.

问题是针对perl的。

For example if I have "hello.world"and the specified character is '.'then the result I want is "hello".

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

回答by Jim Davis

See perldoc -f index:

perldoc -f index

$x = "hello.world";
$y = substr($x, 0, index($x, '.'));

回答by yko

Using substr:

使用substr

my $string = "hello.world";
my $substring = substr($string, 0, index($string, "."));

Or using regexp:

或者使用正则表达式:

my ($substring2) = $string =~ /(.*)?\./;

回答by canavanin

use strict;
use warnings;

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

print "$word\n";

gives you hello

给你 hello

回答by TLP

In the spirit of TIMTOWTDI, and introducing new features: Using the non-destructive option/r

本着 TIMTOWTDI 的精神,并引入新功能:使用非破坏性选项/r

my $partial = $string =~ s/\..*//sr;

The greedy .*end will chop off everything after the first period, including possible newline characters (/soption), but keep the original string intact and remove the need for parens to impose list context (/roption).

贪婪的.*结尾将砍掉第一个句点之后的所有内容,包括可能的换行符(/s选项),但保持原始字符串完好无损,并且不需要括号来强加列表上下文(/r选项)。

Quote from perlop:

来自 perlop 的引用:

If the /r (non-destructive) option is used then it runs the substitution on a copy of the string and instead of returning the number of substitutions, it returns the copy whether or not a substitution occurred. The original string is never changed when /r is used. The copy will always be a plain string, even if the input is an object or a tied variable.

如果使用 /r(非破坏性)选项,则它会在字符串的副本上运行替换,而不是返回替换次数,无论是否发生替换,它都会返回副本。使用 /r 时,原始字符串永远不会改变。即使输入是对象或绑定变量,副本也将始终是纯字符串。

回答by choroba

Another possibility:

另一种可能:

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