我有一个变量如何在perl中使用正则表达式来检查字符串是否包含空格?例如:
$test = "abc small ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters";
因此,对于此字符串,它应检查字符串中的任何单词是否不大于某些x字符。
答案 0 :(得分:5)
#!/usr/bin/env perl
use strict;
use warnings;
my $test = "ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters";
if ( $test !~ /\s/ ) {
print "No spaces found\n";
}
请务必阅读Perl中的正则表达式。
答案 1 :(得分:2)
你应该看看the perl regex tutorial。将他们的第一个“Hello World”示例调整为您的问题将如下所示:
if ("ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters" =~ / /) {
print "It matches\n";
}
else {
print "It doesn't match\n";
}
答案 2 :(得分:2)
die "No spaces" if $test !~ /[ ]/; # Match a space
die "No spaces" if $test =~ /^[^ ]*\z/; # Match non-spaces for entire string
die "No whitespace" if $test !~ /\s/; # Match a whitespace character
die "No whitespace" if $test =~ /^\S*\z/; # Match non-whitespace for entire string
答案 3 :(得分:0)
要查找最长的非空间字符序列的长度,请写下此
use strict;
use warnings;
use List::Util 'max';
my $string = 'abc small ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters';
my $max = max map length, $string =~ /\S+/g;
print "Maximum unbroken length is $max\n";
<强>输出强>
Maximum unbroken length is 61