anand_perl has asked for the wisdom of the Perl Monks concerning the following question:


Hi Monks!!

I need one regular expression to match a string with a space at the beginning and without a space at the beginning

For example,
my $string1 = " <result>"; my $string2 = "<result>";

In the first string there is a white space at the beginning of the string. In the second string there is no white space at the beginning.

I need to match both the strings using a single regular expression

Can anyone help me on this?

Thanks in advance!!!

Replies are listed 'Best First'.
Re: matching white spaces in perl
by SuicideJunkie (Vicar) on Oct 06, 2008 at 14:58 UTC
    Could you simply match against "<result>" and ignore the whitespace?
    Or, trim the leading spaces to make them the same?

    Or, you could check out http://perldoc.perl.org/perlreref.html, in particular, the "?" entry under syntax.
Re: matching white spaces in perl
by Fletch (Bishop) on Oct 06, 2008 at 15:01 UTC

    Of course given the sample data the inevitable followup remark should be, ". . . But you really don't want to use just regexen to parse (SG|X)ML; use a real parser if this is anything other than very simple and a static format."

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      ... and even for simple XML you shouldn't use regexes, because it's not going to stay simple.
Re: matching white spaces in perl
by moritz (Cardinal) on Oct 06, 2008 at 14:54 UTC
    m/\s*<result>/

    Or if you only want one single blank,

    m/ ?<result>

    See perlretut for an introduction to regular expressions.

    Update: as SuicideJunkie++ pointed out, the leading \s* or  ? are pretty pointless unless you either anchor the regex or look at the match variables after the match.

Re: matching white spaces in perl
by JavaFan (Canon) on Oct 06, 2008 at 15:16 UTC
    Well, since any string either has white space at the beginning, or it is without white space at the beginning, the question as you ask it is just "how do I match any string".
    /(?=)/

    Will do that, but that's probably not what you want.

    I could look at your example, but then I'd come up with the regexp:

    /^ ?<result>$/
    That would match the two strings mentioned in the example, and nothing else. Which may be what you want, but I doubt it.

    You know, 98% of the regex questions can be solved by defining what you want - once you do that, the regexp follows easily.