c# - Every keyword needs to be present -


for example, there several sentences:

xx received 2 sent 1
yy received 3 sent 1
zz received 1 sent 3
aa received 4 sent 1

how can find sentences contains 1 and 3?

i need result

yy received 3 sent 1
zz received 1 sent 3

in case.

the closest tried regex r = new regex (".*(3).*(1).*"); not solution.

you can use linq instead of regex:

var strs = new string[] { "xx received 2 sent 1", "yy received 3 sent 1", "zz received 1 sent 3", "aa received 4 sent 1" }; var myres = strs.where(p => p.contains("1") && p.contains("3")).tolist(); 

enter image description here

if prefer regex approach (it slower):

 ^(?=.*1)(?=.*3).* 

see demo (if want use ismatch(), not need .* @ end of pattern).

var rx = new regex(@"^(?=.*1)(?=.*3)"); var myres2 = strs.where(p => rx.ismatch(p)).tolist(); 

the regex matches

  • ^ - start of string , then...
  • (?=.*1) - makes sure there @ least 1 1 start of string
  • (?=.*3) - makes sure there @ least 1 3 (again!) start of string.

the (?=...) construction knows positive look-ahead, 1 of so-called look-arounds:

lookaround matches characters, gives match, returning result: match or no match.

so, when have 2 look-aheads in row, "run" @ same location in input string, , have logical , way. see more in lookarounds stand ground.


Comments