bozo user
bozo user

Reputation: 251

Check for spaces in perl using regex match in perl

I have a variable how do I use the regex in perl to check if a string has spaces in it or not ? For ex:

$test = "abc small ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters";

So for this string it should check if any word in the string is not bigger than some x characters.

Upvotes: 1

Views: 16777

Answers (4)

ikegami
ikegami

Reputation: 385847

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

Upvotes: 3

Borodin
Borodin

Reputation: 126722

To find the length of the longest unbroken sequence of non-space characters, write this

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

output

Maximum unbroken length is 61

Upvotes: 0

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74242

#!/usr/bin/env perl

use strict;
use warnings;

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

Please make sure to read about regular expressions in Perl.

Perl regular expressions tutorial - perldoc perlretut

Upvotes: 6

blahdiblah
blahdiblah

Reputation: 34011

You should have a look at the perl regex tutorial. Adapting their very first "Hello World" example to your question would look like this:

if ("ThisIsAVeryLongUnbreakableStringWhichIsBiggerThan20Characters" =~ / /) {
    print "It matches\n";
}
else {
    print "It doesn't match\n";
}

Upvotes: 3

Related Questions