In Julia, how to reject words with a certain character?

Viewed 151

I want to collect words that do not contain a certain character.

I feel it should be much easier than my current solution (which makes heavy-handed use of regular expressions).

But alas, I'm just not getting it.

Here's my current solution, that works:

want(s) = match(r"\?",s) == nothing
[s for s in lst if want(s)]

Everything else gives me syntax errors:

[s for s in lst if not '?' in s]
[s for s in lst if not ('?' in s)]
filter((x) ->  not ('?' in x),["?asdas","bbb"])

I can do it with a verbose ternary operator:

 filter((x) ->  ('?' in x ? false : true),["?asdas","bbb"])

but that does not seem elegant.

Suggestions?

2 Answers

not is not a valid keyword. the negation operation in julia is !. for example, this code works:

[s for s in lst if !('?' in s)]

The follwing is a more concise variant using filter:

filter(x -> '?' āˆ‰ x, ["?asdas","bbb"])

āˆ‰ is basically just !in, and can be written as \notin. Maybe more efficient (you'd have to test that for your actual data) is to use a regex and match as

filter(x -> isnothing(match(r"\?", x)), ["?asdas","bbb"])
Related