string 从字符串中删除引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5745562/
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
Removing quotes from string
提问by Brandon
So I thought this would just be a simple issue however I'm getting the incorrect results. Basically I am trying to remove the quotes around a string. For example I have the string "01:00" and I want 01:00, below is the code on how I thought I would be able to do this:
所以我认为这只是一个简单的问题,但是我得到了不正确的结果。基本上我试图删除字符串周围的引号。例如,我有字符串“01:00”,我想要 01:00,下面是我认为如何做到这一点的代码:
$expected_start_time = $conditions =~ m/(\"[^\"])/;
Every time this runs it returns 1, so I'm guessing that it is just returning true and not actually extracting the string from the quotes. This happen no matter what is in the quotes "02:00", "02:20", "08:00", etc.
每次运行它都会返回 1,所以我猜它只是返回 true 而不是实际从引号中提取字符串。无论引号“02:00”、“02:20”、“08:00”等中是什么,都会发生这种情况。
回答by tchrist
All you forgot was parens for the LHS to put the match into list context so it returns the submatch group(s). The normal way to do this is:
您忘记的只是 LHS 将匹配项放入列表上下文中的括号,以便它返回子匹配组。执行此操作的正常方法是:
($expected_start_time) = $condition =~ /"([^"]*)"/;
回答by Christoffer Hammarstr?m
It appears that you know that the first and last character are quotes. If that is the case, use
您似乎知道第一个和最后一个字符是引号。如果是这种情况,请使用
$expected_start_time = substr $conditions, 1, -1;
No need for a regexp.
不需要正则表达式。
回答by Jonathan Leffler
The brute force way is:
蛮力的方法是:
$expected_start_time = $conditions;
$expected_start_time =~ s/"//g;
Note that the original regex:
请注意,原始正则表达式:
m/(\"[^\"])/
would capture the opening quote and the following non-quote character. To capture the non-quote characters between double quotes, you'd need some variant on:
将捕获开始引号和以下非引号字符。要捕获双引号之间的非引号字符,您需要一些变体:
m/"([^"]*)"/;
This being Perl (and regexes), TMTOWTDI - There's More Than One Way Do It.
这是 Perl(和正则表达式),TMTOWTDI - 有不止一种方法可以做到。