2012-07-31 36 views
0

我有一個變量如何在perl中使用正則表達式來檢查字符串是否有空格?例如:在perl中使用正則表達式匹配檢查空間perl

$test = "abc small ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters"; 

因此,對於此字符串,它應檢查字符串中的任何單詞是否不大於某些x個字符。

回答

2

你應該看看the perl regex tutorial。適應他們的第一個「Hello World」的例子,你的問題是這樣的:

if ("ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters" =~//) { 
    print "It matches\n"; 
} 
else { 
    print "It doesn't match\n"; 
} 
5
#!/usr/bin/env perl 

use strict; 
use warnings; 

my $test = "ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters"; 
if ($test !~ /\s/) { 
    print "No spaces found\n"; 
} 

請務必閱讀有關Perl的正則表達式。

Perl regular expressions tutorial - perldoc perlretut

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 
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