0

I am trying to extract a string between the two characters @ and : for the string:

test23@server:/var/

So, when I try to do something like, @([^.]*): or even \@(\S+): I get @server:

I just want both @ and : removed so I can get just the word server. Please help!

revo
  • 47,783
  • 14
  • 74
  • 117
new_linux_user
  • 721
  • 1
  • 7
  • 11
  • 2
    (1) With `*` quantifier in `[^.]*` you allow 'nothing' to match as well. You don't say how you use that so I can't tell how it works out but it's probably wrong. (Btw, in a straight-up match it works.) (2) The `\S` is not-a-space, so it matches `:` as well. It will surely work if you limit it (make non-greedy) as `\@(\S+?):` (while it may work otherwise as well, if there are no more `:`) – zdim Mar 01 '18 at 22:48
  • Thank you so much. Yes it did work. I mean making it non-greedy (\@(\S+?):) Thanks a lot! – new_linux_user Mar 01 '18 at 22:51
  • PLease show your whole regex and how you use it – zdim Mar 01 '18 at 22:52
  • (Also, the `[^.]*` attempt should use `[^:]`, to exclude `:` and not `.`) – zdim Mar 01 '18 at 22:58

2 Answers2

1

You only need to use a referrer to capturing group you just constructed or you can use \K token. You don't need to escape @ character and [^.]* means greedily match everything except a literal dot . which is better to be changed to [^:]+:

@\K[^:]+

or more strictly:

@\K[^:]++(?=:)
revo
  • 47,783
  • 14
  • 74
  • 117
0

Try (?<=@).*(?=:). I'm using positive lookbehind and positive lookahead.

It will match anything starting with (but excluding) @ character and ending with (excluding) :

for detail, please see https://www.regular-expressions.info/lookaround.html

see demo at https://regex101.com/r/jIIB9Q/1

Saleem
  • 8,728
  • 2
  • 20
  • 34