Egee
Egee

Reputation: 77

Retrieve characters after nth occurrence of an another with Regex

I'm writing a simple bot that broadcasts messages to clients based on messages from a server. This will be done in JavaScript but I am trying to understand Regex. I've been Googling for the past hour and I've come so close but I am simply unable to solve this one.

Basically I need to retrieve everything between the second / and the first [. It sounds really simple but I cannot figure out how to do this.

Here's some sample code:

192.168.1.1:33291/76561198014386231/testName joined [linux/76561198014386231]

Here's the Regex I've come up with:

\/(.*?)\[

I've found lots of similar questions here on StackOverflow but most of them seem specific to a particular language or end up being too complex and I'm unable to whittle down the query.

I know this is a simple one, but I am totally stumped.

Upvotes: 0

Views: 3333

Answers (1)

vallentin
vallentin

Reputation: 26157

Instead of .*?. Then you could match everything but a forward slash by doing [^\/]*.

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

Live preview

If it needs to be after the second slash. As in the contents between the second slash and the square bracket can contain slashes. Then you could do:

(?:.*?\/){2}(.*)\s*\[

Live preview

Remove the \s* if you want to. I'm just assuming you don't care about that whitespace.

Upvotes: 1

Related Questions