Read from text file and skip some part of text

#1

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.

0 Likes

Read from text file and ignore some part
#2

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?

0 Likes

#3

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.

0 Likes

#4

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

1 Like

#5

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.

1 Like

#6

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.

0 Likes

#7

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"), " ")))
0 Likes

#8

Thank you everyone for your help.

0 Likes