Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match text after a given character excluding the character itself

Tags:

regex

Consider the following text -

[Event "F/S Return Match"]

I want to extract -

F/S Return Match

Right now I'm using -

\"(.*)"

Which yeilds -

"F/S Return Match"

Then I use -

[^"]*

To get -

F/S Return Match

Could I combine the two into one?

like image 262
Kshitiz Sharma Avatar asked Jul 02 '13 15:07

Kshitiz Sharma


People also ask

How do you match a character except one regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).

What does \b mean in regex?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”. This match is zero-length. There are three different positions that qualify as word boundaries: Before the first character in the string, if the first character is a word character.

What does \+ mean in regex?

Example: The regex "aa\n" tries to match two consecutive "a"s at the end of a line, inclusive the newline character itself. Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string.


Video Answer


1 Answers

Look-around could be an option:

(?<=")[^"]*(?=")

(?<=") checks that the previous character is a ".
(?=") checks that the next character is a ".

Test.

An alternative is just to use grouping:

"([^"]*)"

How to extract the group is dependent on the language used.

Test. (note the "Matching groups" area)

I didn't simply use "(.*)" because the string abc "def" "ghi" will match "def" "ghi", though you may have wanted to match "def" and "ghi" separately. An alternative to [^"] is non-greedy matching - "(.*?)", which will match as little of the string as possible.

like image 114
Bernhard Barker Avatar answered Nov 08 '22 09:11

Bernhard Barker