mark
mark

Reputation: 873

Regex finding second string

I'm attempting to get the last word in the following strings.

After about 45 minutes I can't seem to find the right combination of slashes, dashes and brackets.

The closest I've got is

/(?![survey])[a-z]+/gi

It matches the following strings, except for "required" it is returning the match "quired" I'm assuming it's because the re are in the word survey.

survey[1][title]
survey[1][required]
survey[2][anotherString]

Upvotes: 1

Views: 61

Answers (2)

Liinux
Liinux

Reputation: 173

One way to solve this is to match the full line and only capture the part you need.

survey\[\d+\]\[([a-z]+)\]

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370889

You're using a character set, which will exclude any of the characters from being the first character in the match, which isn't what you want. Using plain negative lookahead would be a start:

(?!survey)[a-z]+

But you also want to match the final word, which can be done by matching word characters that are followed with \]$ - that is, by a ] and the end of the string:

[a-z]+(?=\]$)

https://regex101.com/r/rLvsY5/1

If you want to be more efficient, match the whole string, but capture what comes between the square brackets in a capturing group - the last repeated captured group will be in the result:

survey(?:\[(\w+)\])+

https://regex101.com/r/rLvsY5/2

Upvotes: 2

Related Questions