David
David

Reputation: 13

Regular Expression how to get the value inside double quotes including double quotes

This is want I want to achieve

a) (123) => 123

b) ("123") => 123

c) ""123"" => "123"

d) (""#12.20.AA"") => "#12.20.AA"

valid characters inside the first double quotes are ", ., # and :

I tried with this [\w\"\.:#=/\-\+\t\s]+ but obviously is returning ""123"" for the case b and ""#12.20.AA"" for case c and "123" for case b.

Any idea how to avoid the first double quotes and only the fist (and the same in the tail)?

Upvotes: 1

Views: 75

Answers (2)

matteo rulli
matteo rulli

Reputation: 1493

This expression works for me:

\(?.*?"?("?[#:\d\.AA]+("(?="))?)"?.*\)?

You get your matches in the first matching group. The same regex with some comments:

\(?
.*?               # ? prevent the * to be eager
"?                # include the " if there
(                 # group 1 (your match)
    "?[#:\d\.AA]+
    ("(?="))?     # positive lookahead: include the first " in case there are two of them
)
"?
.*\)?

At this demo link you can easily experiment further with this expression.

In general, in case you need authoritative info on regex, this is a pretty good link.

Hope this helps.

Upvotes: 1

Dmitry Mitko
Dmitry Mitko

Reputation: 1

if ($txt =~ /"/) {
    s/^[^"]*"//;
    s/"[^"]*$//;
}

Upvotes: 0

Related Questions