简体   繁体   English

用Perl中的空格匹配子字符串

[英]Match Substring with spaces in perl

I am trying to match a sub-string with a given string in perl. 我正在尝试将子字符串与perl中的给定字符串进行匹配。

Match is failing when the sub-string contains space. 子字符串包含空格时,匹配失败。

Example: 例:

Please consider the following string variable: 请考虑以下字符串变量:

var = "test [abc], def, xyz,"

The expression: 表达方式:

($var=~ m/test [abc]/)

doesn't return 1. 不返回1。

Strings without spaces are working fine: 没有空格的字符串可以正常工作:

Example:

($var=~ m/def/)

is returning 1.

Please help. 请帮忙。

Thanks 谢谢

[ and ] in regex have special meaning. 正则表达式中的[]具有特殊含义。 They define character classes. 他们定义字符类。 If you want to match a [ or a ] , you need to escape them: 如果要匹配[] ,则需要对它们进行转义:

$var=~ m/test \[abc\]/

[] are character class in regex. []是正则表达式中的字符类。 you have to escape those: 您必须逃脱那些:

($var=~ m/test \[abc\]/)

In your example test [abc] will match test a , test b or test c . 在您的示例中, test [abc]将匹配test atest btest c Cause [abc] means any of a,b,c 原因[abc]表示a,b,c任何a,b,c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM