How to search multiple strings in a string?

偶尔善良 提交于 2019-12-05 07:05:29

This is a case where you'll want to combine a few M library functions together.

You'll want to use Text.Contains many times against a list, which is a good case for List.Transform. List.AnyTrue will tell you if any string matched.

List.AnyTrue(List.Transform({"dog","string","bark"}, (substring) => Text.Contains("This is a test string", substring)))

If you wished that there was a Text.ContainsAny function, you can write it!

let
    Text.ContainsAny = (string as text, list as list) as logical =>
        List.AnyTrue(List.Transform(list, (substring) => Text.Contains(string, substring))),
    Invoked = Text.ContainsAny("This is a test string", {"dog","string","bark"})
in
    Invoked

Another simple solution is this:

List.ContainsAny(Text.SplitAny("This is a test string", " "), {"dog","string","bark"})

It transforms the text into a list because there we find a function that does what you need.

Lukasz P.

If it's a specific (static) list of matches, you'll want to add a custom column with an if then else statement in PQ. Then use a filter on that column to keep or remove the columns. AFAIK PQ doesn't support regex so Alexey's solution won't work.

If you need the lookup to be dynamic, it gets more complicated... but doable you essentially need to

  1. have an ID column for the original row.
  2. duplicate the query so you have two queries, then in the newly created query
  3. split the text field into separate columns, usually by space
  4. unpivot the newly created columns.
  5. get the list of intended names
  6. use list.generate method to generate a list that shows 1 if there's a match and 0 if there isn't.
  7. sum the values of the list
  8. if sum > 0 then mark that row as a match, usually I use the value 1 in a new column. Then you can filter the table to keep only rows with value 1 in the new column. Then group this table on ID - this is the list of ID that contain the match. Now use the merge feature to merge in the first table ensuring you keep only rows that match the IDs. That should get you to where you want to be.

Thanks for giving me the lead. In my own case I needed to ensure two items exist in a string hence I replaced formula as:

List.AllTrue(List.Transform({"/","2017"},(substring) => Text.Contains("4/6/2017 13",substring)))

it returned true perfectly.

You can use regex here with logical OR - | expression :

/dog|string|bark/.test("This is a test string") // retruns true
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!