1

I'm trying to extract the second last value in a string so I can return the value "Minute". I'm using Zapier which only allows regex.

Example string:

Week,Day,Hour,Another,Hour,Minute,Second

I've got a positive lookahead working below that returns the value "Second", however I cannot figure out how to apply an n-1 style operator to return the second-last string value "Minute".

My regex:

(?!^\,)[^,]*$

Try it here: https://regex101.com/r/mXVg6W/1

Any ideas?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
pulpassets
  • 21
  • 3
  • In what cases the tags `regex-lookarounds` and `regex-groups` should be specifically used? @WiktorStribiżew – lemon Jul 04 '22 at 19:36
  • 1
    @lemon When the question is specific about these constructs. Here, no capturing groups are in question. Lookarounds are not the focus point here either, it is used, but OP just used it as a guess, without understanding what they are doing. The only problem is regex in general here, just the pattern. – Wiktor Stribiżew Jul 04 '22 at 20:05

3 Answers3

2

You can use the following regex:

[^,]+(?=(?:,[^,]+){1}$)

It extracts the first non-comma values [^,]+ occurring after a comma, a sequence of non-comma values and the end of string (?:,[^,]+){1}$. If you want preceeding values, it's sufficient to increment the value inside of the braces (the amount of ,string to be passed over).

Check the demo here.

lemon
  • 14,875
  • 6
  • 18
  • 38
  • This works very neatly, thanks! If I wanted to adjust which position I extracted the string from, say to return "Hour" or "Another", could your regex be manipulated to do that? – pulpassets Jul 04 '22 at 19:14
  • Updated the answer accordingly. – lemon Jul 04 '22 at 19:19
1

How about letting the dot consume and capture (no lookarounds).

.*,([^,]+),

See this demo at regex101

Obviously this only makes if at lesat two commas occure in the string.

bobble bubble
  • 16,888
  • 3
  • 27
  • 46
0

Does this work? [\d+\,]{9}(\d)[\,\d]

Ryan Penfold
  • 752
  • 2
  • 11
  • 16