secr
secr

Reputation: 2883

How can I match quoted text excluding leading and trailing whitespaces?

I.e. the match of

 He said, "For my part, it was Greek to me. "

should be

For my part, it was Greek to me.

Without the trailing space. I've tried

\"\s*([^\"]*)\s*\"

but it's always matching trailing whitespaces in the group.

Upvotes: 0

Views: 1252

Answers (3)

user54650
user54650

Reputation: 4426

try:

\"\s*([^\"]*?)\s*\"

But be careful, this version is contingent upon the closing quotation mark (because it's lazy). When you add the lazy operator here, it grabs the smallest possible string it can. If there are no closing quotes, this regular expression will fail

If you're sure there's no empty strings, you can use:

\"\s*([^\"]*[^\"\s])\s*\"

The main problem with this version is that you are now pushing for a minimum of one character.

Honestly, looking at it twice, I'd use the first pattern. You're looking for the closing quote and not escaping any quotes. It'll work 100% of the time for your current needs.

Upvotes: 2

Ben
Ben

Reputation: 68588

What about if you force it to have the final character be non-white space? Something like this:

\"\s*([^\"]*[^\s])\s*\"

Upvotes: 0

Sebastian Dietz
Sebastian Dietz

Reputation: 5706

Wouldn't it be easier to just trim the blanks afterwards using simple string functions? This would also simplify the regular expression.

Upvotes: 1

Related Questions