Home > Back-end >  Regex for tickers on stock and crypto market
Regex for tickers on stock and crypto market

Time:08-26

I am struggling to create a functional regex with the following criteria:

  • Identify a MAX of 5 lowercase characters ONLY after a '$' sign and before a space OR at the end of a sentence (empty string or peroid '.')

  • AND match a MAX of 5 UPPERCASE letters with OR without a '$' sign at the front that HAVE to be followed by a space, symbol (comma, exclamation) or be at the end of a sentence (empty string or peroid '.')

  • If there is a match of any kind

Examples of matches

"The $APPL fell on the TSLA." (should match $APPL and TSLA) "$gme is an APEs game" (should only match $gme) "This a game of $money. Where LAMBO" (should match $money and LAMBO)

I have been playing with the following, getting some parts to work but never all in one:

const found = [
    "this is an APPL",
    "this is an APPL.",
    "this is an $APPL",
    "this is an $appl",
    "this is an $appl.",
    "this is an $appl and orange.",
    "this is an $appl, and orange.",
    "this is an $APPL and orange.",
    "this is an $APPL, and orange.",
    "this is an APPL! and orange."
];

const notFound = [
    "this is an appl.",
    "this is an $applasdfasdf.",
    "this is an APPLLLLLL",
    "this is an $APPLLLLLL"
];

const matchTicker = /[$][A-Za-z]{0,5}/;

// Should evaluate to TRUE
console.log("\nFOUND\n");
found.forEach((ticker) => {
    console.log(matchTicker.test(ticker));
});

// Should evaluate to FALSE
console.log("\nNOT FOUND\n");
notFound.forEach((ticker) => {
    console.log(matchTicker.test(ticker));
});

CodePudding user response:

Would this work for you:

\$[a-z]{2,5}\b|\$?\b[A-Z]{2,5}\b

RegEx Demo

RegEx Explanation:

  • \$[a-z]{2,5}\b: first case with lowercase letters
  • |: or
  • \$?\b[A-Z]{2,5}\b: second case with uppercase letters
  • Related