Read from text file and skip some part of text

I have a text file which has below format
4 ! nx, ny
25 !x, y
I want to read only the integer values and assign it to variables. I want to ignore the whitespace and the text after !. I tried using readline command. But it takes the whole line. How can I read just numbers on each line? Thank you.

1 Like

You can read the whole line and then do stuff with it then. Is this performance critical where its necessary to not read too much?

No, it is not performance critical. Do you have any suggestions on how I can split the string into two parts, integer and string (which will be discarded)? I am totally new to Julia. Thank you.

The typical way to do this is to use a regular expressions.

2 Likes

And if you aren’t familiar with regular expressions, regex101 is your friend. Try a tutorial first here.

The way Julia implements regular expressions is very standardized and useful.

2 Likes

you could

fields = split(line, " ")
n = parse(Int, fields[1])

or

m = match(r"^([0-9]+)", line)
if m == nothing
  error("integer not found")
end
n = parse(Int, m[1])

Note that i’ve written the regular expression such that the integer value must be at the beginning of the line. if there might be spaces then

r"^ *([0-9]+)"

will work. Generally you want to write regular expressions as “tightly” as possible, otherwise they may match something but not what you were expecting.

1 Like

Read all lines, split by space, take the first element, parse as integer:

readlines("sample.txt") .|> s -> parse(Int, split(s, " ")[1])

You can also use the dot notation:

parse.(Int, first.(split.(readlines("sample.txt"), " ")))

Thank you everyone for your help.