簡體   English   中英

使用Perl中的正則表達式匹配檢查Perl中的空格

[英]Check for spaces in perl using regex match in perl

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

$test = "abc small ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters";

因此,對於此字符串,應檢查字符串中是否有不超過x個字符的單詞。

#!/usr/bin/env perl

use strict;
use warnings;

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

請確保閱讀有關Perl中的正則表達式的信息。

Perl正則表達式教程perldoc perlretut

您應該看一下perl regex教程 根據他們的問題改編他們的第一個“ Hello World”示例將如下所示:

if ("ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters" =~ / /) {
    print "It matches\n";
}
else {
    print "It doesn't match\n";
}
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

要查找最長的不間斷非空格字符序列的長度,請編寫以下代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM