0

Let's say I have the below test data

Home$Fruits
Home$Fruits$Apple
Home$Fruits$Apple$Red-Apple
Home$Fruits$Apple$Green-Apple
Home$Fruits$Banana$Yellow-Banana
Home$Fruits$Banana$Green-Banana
Home$Fruits$Orange

I want to match those lines that has $ symbol exactly 2 times (or exactly 'n' times). What would be the possible regex?

Any help is really appreciated.

aswath86
  • 551
  • 5
  • 14
  • 1
    Does the amount need to equal 'n' exactly, or just have at least that many '$'s? – Rob Streeting Sep 03 '19 at 13:34
  • With regex, you will have a tough time avoiding false matches for lines that have more than the specified number of symbols to match. It should be much easier with other string handling techniques. For example, in javascript this function will return a list of matching lines given the text and number of dollar symbols: `(text, dollars)=> text.split('\n').filter(line => [...line].filter(character => character === "$").length === dollars)`. – Patrick Stephansen Sep 03 '19 at 13:39
  • Be it exactly two or two or more, the difference is in the limiting quantifier only, the approach is [the same](https://stackoverflow.com/questions/50522918/how-to-match-string-that-contain-exact-3-time-occurrence-of-special-character-in). – Wiktor Stribiżew Sep 03 '19 at 13:41
  • @Aswath You don't seem to be sure about your requirement as you keep changing it. – 41686d6564 stands w. Palestine Sep 03 '19 at 13:44

2 Answers2

5

You may use the following pattern:

^(?:[^$\r\n]*\$[^$\r\n]*){2}$

Demo.

You may replace {2} with {n} where n is the number of occurrence of the "$" symbol. You could also use {n,} to match n or more times.

Demo for two or more times.

0

Try matching on the following pattern:

^.*\$.*\$.*$

This matches (at least) two $, anywhere in a given line.

Demo

This pattern will only work as expected if dot all mode is not enabled. Otherwise, the .* might trace across more than one line.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360