Julia for regular expression strings in grep file

I would like to see a julia code snippet that will read the file and return strings (string type) that match the regular expression.

I welcome a few methods, but the output should be equivalent to the following:

$> grep -E ^AB[AJ].*TO' 'webster-unabridged-dictionary-1913.txt'

ABACTOR
ABATOR
ABATTOIR
ABJURATORY

I use GNU grep 3.1 here, and the first line of each entry in the file is all the words caps.

+4
source share
3 answers

My favorable solution uses a simple loop and is very easy to understand.

julia> open("webster-unabridged-dictionary-1913.txt") do f
           for i in eachline(f)
               if ismatch(r"^AB[AJ].*TO", i) println(i) end
           end
       end

ABACTOR
ABATOR
ABATTOIR
ABJURATORY

Notes

  • Tab delimited lines have saved tabs (no literal output '\ t')
  • my source file in this example contains dictionary words only in all caps on the same line above the definition; full string is returned.
  • - , , lamba x -> f(x) . file open(), try-finally-close .
  • Julia docs: /
    • regex r"<regex_literal_here>"
    • perl PCRE

julia> reg = r"^AB[AJ].*TO";
julia> typeof(reg)
Regex

julia> test = match(reg, "ABJURATORY")
RegexMatch("ABJURATO")

julia> typeof(test)
RegexMatch
+3

filter, .

filter(line -> ismatch(r"^AB[AJ].*TO",line),readlines(open("webster-unabridged-dictionary-1913.txt")))

filter , Boolean , , true. line -> ismatch(r"^AB[AJ].*TO",line)", , ( ) line.

, , , , for, eachline. , , , , , .

+2

Just placing ;in front is a way to use Julia command line commands, so this works in Julia REPL

;grep -E ^AB[AJ].*TO' 'webster-unabridged-dictionary-1913.txt'
+1
source

Source: https://habr.com/ru/post/1689028/


All Articles