What regex expression would I need in order to extract S{}fAct from input?

Viewed 46

Input string:

S{WCS-STD}bUsr | S{logan}bUid | S{%24contact_person_id%24}sCmd | S{}sId | A{}sNme | S{}sUrl | S{}sLbl | S{}sCok | S{}mMsg | S{test}fAct | S{}fTyp | S{}fKey | S{}fVal | S{}bUserType | S{CUST}transType | S{}mTsp | S{2017-12-19 18:54:49}mDeptId | S{999}bPvtMsg | S{0}bToPvt | S{null}mOffRecord | S{null}entityName | S{null}}|

String to identify:

S{test}fAct (the value between the brackets is alphanumeric)

Question How can I extract the string listed above with a Regex expression? I am a novice with regex and need help creating the correct expression.

I have tried the following but am unable to only select the S{}fAct attribute:

\| S{.+}fAct \|

Example: https://regex101.com/r/uefLBA/1

3 Answers

Regex:

^.+(S\{(.+[a-zA-Z0-9])\}fAct).+$

Explanation:

  • ^ - Start of string
  • .+ - One or more characters before S{test}fAct
  • .+[a-zA-Z0-9] - One or more alphanumeric
  • .+ - One or more characters after S{test}fAct
  • $ end of string

Regex tester https://regex101.com/r/m8068B/1

For the cleanest solution, I recommend @Sach's answer. However, if you don't want to deal with capturing groups, here's an alternate solution which only matches the S{test}fAct portion:

.+(?=S{.+}fAct)\KS{.+}fAct

Explanation:

  • .+ Matches as many characters as it can
  • (?=S{.+}fAct) A positive lookahead - constrains the match so that it has to stop before your desired string
  • \K Consumes all characters matched so far so they will not be included in the final match
  • S{.+}fAct Now we can just match the desired string, since we already consumed everything that wasn't part of it.

Example: https://regex101.com/r/THJ1cu/1

Please note that this is far from the cleanest solution.

You can match | , then capture the value you want in a capturing group and assert what is on the right side is again |

Using a positive lookahead allows matching the same pattern in case it occurs right after it and you want both to match.

\| (S{[A-Za-z0-9]+}fAct)(?= \|)

Explanation

  • \| Match a pipe and space
  • ( Capture group 1
    • S{[A-Za-z0-9]+} Match S{, then 1+ alphanumberic chars followed by } The + prevents an empty {}, if that is allowed use an * instead.
  • fAct Match literally
  • ) Close group 1
  • (?= \|) Positive lookahead, assert what is directly to the right is a space and pipe

Regex demo

Related