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

Hi Monks,

I wonder how can I check whether a string exactly one quotation mark " contains. If I use /"/ that means at least one...

BR

Replies are listed 'Best First'.
Re: Perl Matching
by Corion (Patriarch) on Oct 24, 2013 at 11:19 UTC

    Maybe it helps if you rephrase your problem?

    Check whether a string contains characters that are not a quotation mark, then a single quotation mark, and then only characters that are not a quotation mark

    If you look at your problem that way, you should convince yourself that it is equivalent to "string contains exactly one quotation mark", and it should also be fairly easy to translate that to a regular expression.

      Slight restatement:

      Check whether a string optionally contains characters that are not a quotation mark, then a required single quotation mark, and then, optionally, only characters that are not a quotation mark

      But yes, Corion's answer should get you on the right track.


      Mike
Re: Perl Matching
by Laurent_R (Canon) on Oct 24, 2013 at 11:46 UTC

    The easiest might be to count the quotes with a function such as tr:

    my $count = $string =~ tr/"/"/;

    It could also be done with s///, but likely to be slightly slower.

Re: Perl Matching
by Ratazong (Monsignor) on Oct 24, 2013 at 11:48 UTC

    Try index:

    1. find the position of the first quotation mark in your string
    2. (if there is one): find the position of the next quotation mark, starting your search at the position determined in step 1
    HTH, Rata
Re: Perl Matching
by Lennotoecom (Pilgrim) on Oct 24, 2013 at 13:07 UTC
    $_ = 'a"b"c"d'; $a = () = /"/g;
    now $a contains exactly amount of "s in the $_. though I suspect there is a better and shorter way