Reputation: 370
Lets say I have a string something-123.
I need to get last 5 (or less) characters of it but only up to - if there is one in the string, so the result would be like thing, but if string has no - in it, like something123 then the result would be ng123, and if string is like 123 then the result would be 123.
I know how to mach last 5 characters:
/.{5}$/
I know how to mach everything up to first -:
/[^-]*/
But I can not figure out how to combine them, and to make things worse I need to get the match without extracting it from specific groups and similar advanced regex stuff because I want to use it in SQL Anywhere, please help.
Tank you all for the help, but looks like a complete regex solution is going to be too complicated for my problem, so I did it very simple: SELECT right(regexp_substr('something-123', '[^-]*'), 4)
.
Upvotes: 2
Views: 111
Reputation: 627468
You can use:
.{5}(?=(?:-[^-]*)?$)
See the regex demo
We match 5 symbols other than a newline only before the last -
in the string or at the very end of the string ((?=(?:-[^-]*)?$)
). You only need to collect the matches, no need checking groups/submatches.
UPDATE
To match any 1 to 5 characters other than a hyphen before the first hyphen (if present in the string), you can use
([^-]{1,5})(?:(?:-[^-]*)*)?$
See demo. We rely on a lookahead here, that checks if there are -
+non-hyphen
sequences are after the expected substring.
^[^-]*?([^-]{1,5})(?:-|$)
This regex will search for any characters other than -
up to 1 to 5 such characters.
Note that here, the value we need is in Group 1.
Upvotes: 1
Reputation: 439
Try this regex:
(.{1,5})(?:-.*|$)
Group 1 has the result you need
Upvotes: 1
Reputation: 96018
One option is to group the result:
(.{4})-
Now you have captured the result but without the -
.
Or using lookarounds you can:
.{4}(?=-)
which matches any 4 characters that appears before "-".
Upvotes: 2