Python Forum
Facing issue in python regex newline match - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Facing issue in python regex newline match (/thread-40910.html)



Facing issue in python regex newline match - Shr - Oct-12-2023

Hi Everyone,

.Myc PGGGGG_UIII_Q9999_AB A0 B11 B22 D1 D2 D3
+ 4I 3B

I am trying to match the above two line using regex.

\.(myc|Myc)\s+([a-zA-Z0-9\_\-]+)\s+(.*)\n(.*) = Used this regex

It will print --> .Myc PGGGGG_UIII_Q9999_AB A0 B11 B22 D1 D2 D3

It is not going to newline(\n is NOT WORKING HERE). Please let me know how to go to newline in python regex.
Suggestions are appreciated.

Thank you!


RE: Facing issue in python regex newline match - deanhystad - Oct-12-2023

Please post your code. I don't know what re command you are using or what arguments are passed other than the pattern. Are you using the MULTILINE flag?


RE: Facing issue in python regex newline match - Shr - Oct-13-2023

[quote="deanhystad" pid='173623' dateline='1697137364']
Please post your code. I don't know what re command you are using or what arguments are passed other than the pattern. Are you using the MULTILINE flag?
I am using re.compile:

re.compile(r''\s*^\.(myc|Myc)\s+([a-zA-Z0-9\_\-]+)\s+(.*)\n(.*)") -- But after lot of research I got to know that the raw string(r") used here won't consider \n as new line, it treats \n as \n itself. But I don't know how to remove raw string here.

And I tried using re.M, re.DOTALL and it didn't work, please let me know what needs to be done.


Python newline match - Shr - Oct-13-2023

How to match new line in python regex. ( if \n DOES'NT WORK)


RE: Facing issue in python regex newline match - deanhystad - Oct-13-2023

https://stackoverflow.com/questions/14689531/how-to-match-a-newline-character-in-a-raw-string


RE: Facing issue in python regex newline match - snippsat - Oct-13-2023

Added r.
import re

input_string =\
""".Myc PGGGGG_UIII_Q9999_AB A0 B11 B22 D1 D2 D3
+ 4I 3B"""

pattern = r'\.(myc|Myc)\s+([a-zA-Z0-9\_\-]+)\s+(.*)\n(.*)'
matches = re.findall(pattern, input_string)[0]
print(matches)
Output:
('Myc', 'PGGGGG_UIII_Q9999_AB', 'A0 B11 B22 D1 D2 D3', '+ 4I 3B') >>> matches[0] 'Myc' >>> matches[-1] '+ 4I 3B'



RE: Facing issue in python regex newline match - Shr - Oct-25-2023

Thanks everyone! Thanks a lot @snippsat
I will try and update the result.