Reputation: 261
I want to check in a powerquery new column if a string like "This is a test string"
contains any of the strings list items {"dog","string","bark"}
.
I already tried Text.PositionOfAny("This is a test string",{"dog","string","bark"})
, but the function only accepts single-character values
Expression.Error: The value isn't a single-character string.
Any solution for this?
Upvotes: 7
Views: 24567
Reputation: 6999
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
Upvotes: 14
Reputation: 2229
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
Upvotes: 1
Reputation: 53
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.
Upvotes: 0
Reputation: 1588
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.
Upvotes: 4
Reputation: 233
You can use regex here with logical OR - |
expression :
/dog|string|bark/.test("This is a test string") // retruns true
Upvotes: -2