-2

I'm struggling to find lines that contain 3 or more of a specified character.

Example Problem:

I want to filter this list to output all lines that contain at least 3 plus signs

Example Dataset:

+1a
+1a +2
+1a +2 +3
+1a +2 +3 +4
+1a +2 +3 +4 +5

Desired Output:

+1a +2 +3
+1a +2 +3 +4
+1a +2 +3 +4 +5

I need to check for plus signs. Thanks for your help.

3 Answers3

0

Use this Regular Expression:

((.*\+.*){3,})

Demo here.

Ankit
  • 682
  • 1
  • 6
  • 14
0

In perl:

my $a = "+1 +2";
my $b = "+1 +2 +3";

if($a =~ m/(\+.*){3}/) { print("a: yes\n"); }
else                   { print("a: no\n");  }

if($b =~ m/(\+.*){3}/) { print("b: yes\n"); }
else                   { print("b: no\n");  }

outputs:

a: no
b: yes

The regex used is (\+.*){3}. To break down:

(\+.*)    --- A plus sign ("\+", "+" is a special symbol in perl, so escape it),
              followed by any characters (".") of zero or arbitrary length ("*").
              Enclose the above character sequence in "(" and ")" to make it a pattern unit.
{3}       --- Repeat the above pattern unit 3 times.

The format of regex may differ if using other tools/languages.

Light
  • 1,206
  • 1
  • 9
  • 16
-1

If you are not obliged to use a regular expression a simple language construct would seem to be a better choice. In Ruby, for example, if str.count('+') > 2 .... I will assume, however, that a regular expression is needed.

If you want the entire string matched if it contains three or more plus signs you can use the regular expression

^(?:[^+\n]*\+){3}.*

or

^(?=(?:[^+\n]*\+){3}).*

See Demo 1 and Demo 2

(^(?=(?:.*\+){3}).* could be used in place of the latter but is less efficient.) Demo 3

If you merely want any match if (and only if) the string contains three or more plus signs, you may use

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

Demo 4

See the links for a detailed description of the function of each token in each regex.

Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100