Ali
Ali

Reputation: 10453

Regex match string in double or single quote and follow by space

I'm trying to match string which can be between single or double quote and must follow with a specific text.

input:

<title ng-bind="'key_name' | i18n"></title>

or can be

<span class="sr-only">{{ 'key_name' | i18n }}</span>

or

<span class="sr-only">{{ "key_name" | i18n }}</span>

I want to capture that key_name

This is what I have so far but failed.

["']([^)]+)["']\s|\si18n

Upvotes: 1

Views: 1424

Answers (4)

Alan Moore
Alan Moore

Reputation: 75222

Is the substring in the quotes always a single word, like key_name? If so, this should be all you need:

(["'])(\w+)\1\s*\|\s*i18n\b

If not, this might set you right:

(["'])([^'"]+)\1\s*\|\s*i18n\b

In either case, the part you're looking for will be captured in group #2. If your needs are more complicated than this, we'll need more info.

Upvotes: 0

Oscar Mederos
Oscar Mederos

Reputation: 29823

The following regex should work for you:

["']([^"']+?)['"]\s*\|\s*i18n

Check here:

http://regex101.com/r/aI1lX4

Upvotes: 1

tommoyang
tommoyang

Reputation: 339

.*(["'])([^)]*?)\1\s*?\|\s*?i18n

Regular expression visualization

Debuggex Demo

".*" in the beginning is required to match the least number of characters as possible. Backreference to the first capture is to ensure that both quotes match. Any number of whitespace is permissible around the "|". This is assuming no unescaped quote marks are within the text you want to capture, though. The match result is in $2, as $1 is used to maintain the quote marks.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

This expression will work for the three examples you posted, but it is altogether not very flexible.

/(?:\{\{\s*|"\s*(?=')|'\s*(?="))((['"]).*?\2)\s\|\si18n/
// Without capturing quotes:
/(?:\{\{\s*|"\s*(?=')|'\s*(?="))(['"])(.*)?\1\s\|\si18n/

The actual match will be in [1] and [2], respectively. You may want to change some of the \s to \s* or \s+.

Upvotes: 1

Related Questions