Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

python - regular expression on stream instead of string?

Suppose you want to do regular expression search and extract over a pipe, but the pattern may cross multiple lines, How to do it? Maybe a regular expression library work for a stream?

I hope do this job using Python library? But any solution will be OK, a library not a cmd line tool of course.

BTW, I know how to solve my current problem, just seeking a general solution.

If no such libray exists, why regular library can not work with stream given the regular mathing algorithm never need backward scaning.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are after a general solution, your algorithm would need to look something like:

  1. Read a chunk of the stream into a buffer.
  2. Search for the regexp in the buffer
  3. If the pattern matches, do whatever you want with the match, discard the start of the buffer up to match.end() and go to step 2.
  4. If the pattern does not match, extend the buffer with more data from the stream

This could end up using a lot of memory if no matches are found, but it is difficult to do better in the general case (consider trying to match .*x as a multi-line regexp in a large file where the only x is the last character).

If you know more about the regexp, you might have other cases where you can discard part of the buffer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...