Regex to detect preferred stock symbols

Viewed 70

To start off, regex is probably the least talented aspect within my programming belt, this is what I have so far:
\D{1,5}(PR)\D+$

\D{1,5} because common stock symbols are always a maximum of 5 letters
(PR) because that is part of the pattern that needs to be searched (more below in the background info)
\D+$ because I'm trying to match any single letter at the end of the string

A small tidbit of background
Preferred stock symbols are not standardized and so every platform, exchange, etc has their own way to display them. Having said that, most display a special character in their name, which makes those guys easy to detect. The characters are
[] {'.', '/', '-', ' ', '+'};
The trickier ones all have a similar pattern:
{symbol}PR{0}
{symbol}p{0}
{symbol}P{0}
Where 0 is just any single letter A-Z

Here is a sample data set for the trickier ones:

PSAPRZ
PSApA
PSApZ
PSAPA
PSAPZ

My regex seems to be working for the first one, since I'm specifically looking for (PR) and matching any single letter character at the end, but I can't for the life of me figure out how to also detect the patterns that end in p{0} or P{0} in the same regex. I completely gave up trying to incorporate finding the special symbols because I can easily just do a string.Contains on the target string for any of those chars. The more important part is figuring out these trickier ones.

How do I get my regex statement to also detect the p{0} and P{0} matches within the same regex statement?

Edit 1 If you're curious at the madness of different possibilities, including the "easy to detect" versions, grab a popcorn, here you go :)

PSA.PA
PSA.PR.A
PSA/PA
PSAPRA
PSA-A
PSA PRA
PSA.PRA
PSA.PA
PSA+A
PSA/PRA
PSApA
PSAPA
PSA-PA
1 Answers

This should do it:

^[A-Z]{1,5}([Pp]|PR)[A-Z]$

Explanation:

  • ^ - anchor at start
  • [A-Z]{1,5} - one to five uppercase letters
  • ([Pp]|PR) - capture group used for: uppercase P or lowercase p or uppercase PR
  • [A-Z] - one uppercase letters
  • $ - anchor at end

UPDATE after EDIT 1 in question. To support the odd formats with ., /, -, + use this:

^[A-Z]{1,5}[.\/\s\+\-]?([Pp]|PR\.?)[A-Z]$

Explanation:

  • ^ - anchor at start
  • [A-Z]{1,5} - one to five uppercase letters
  • [.\/\s\+\-]? - optional single character ., /, , +, -
  • ([Pp]|PR\.?) - capture group used for: uppercase P, or lowercase p, or uppercase PR followed by optional .
  • [A-Z] - one uppercase letters
  • $ - anchor at end

Note on anchors: Use ^...$ anchors if you only have the stock symbol in the string. If you have text with a stock symbol anywhere within, use word boundaries \b...\b instead.

Learn more about regex: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex

Related