-1

I have to find a pattern in a string and only keep the middle part if the pattern matches.

The pattern is below:

(space)(↳)(space)(any characters, numbers symbols etc)(space)(-)(space)(currency symbol, could be £$ etc)(1 or many digits)(.)(2 digits)

↳ Add milk - £0.25

If the pattern matches I want to keep (any characters, numbers symbols etc) and discard everything else.

Is it possible?

1

1 Answer 1

1

\s↳\s(.+)\s-\s([\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6]\d+\.\d{2}) should work. The long, horrible part in the middle is to find the currency symbol, taken from this answer.

Piece by piece:

  • \s matches a whitespace character
  • matches that character exactly
  • \s matches a whitespace character
  • (.*) is your first capture group, and catches everything until the next part of the Regex is matched. .* means any character, any number of times.
  • \s-\s matches a whitespace followed by a dash and another whitespace
  • ([\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6]\d+\.\d{2}) catches the currency and digits:
    • [\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6] matches a currency character
    • \d+\.\d{2} matches one or more digit, followed by a full stop and two more digits

In context:

let regex = /\s↳\s(.+)\s-\s([\$\xA2-\xA5\u058F\u060B\u09F2\u09F3\u09FB\u0AF1\u0BF9\u0E3F\u17DB\u20A0-\u20BD\uA838\uFDFC\uFE69\uFF04\uFFE0\uFFE1\uFFE5\uFFE6]\d+\.\d{2})/;

let testText = " ↳ Add milk - £0.25";
let matches = regex.exec(testText);

console.log("Test text = \"" + matches[0] + "\"");
console.log(matches[1]);
console.log(matches[2]);

If you only want to match on a couple of currencies, say £ or $, you will make your life much easier and the regex will look much less ugly.

Sign up to request clarification or add additional context in comments.

1 Comment

Sweet! Exactly what I wanted. Modified it slightly to cater some extra circumstances but works well. Cheers mate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.