new line and regex

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
bazkeys
Posts: 98
Joined: 20 Jan 2021, 21:58

new line and regex

Post by bazkeys » 24 Jul 2021, 21:05

I'm getting confused with checking for new line in reg ex. I don't care how the newline was created, whether it was generated as output by some program or manually by a user with a carriage return.

I've got bits of code using \n (newline)
example

Code: Select all

Found_pos_orig := RegExMatch(aFileContents,"`am)^.*(?=: paid the invoice\d+\n^.*\: paid\d+ and on time)", str_purchaser, pos)
after manually editing the text file the above code stopped working, until after much hair tearing I replaced \n with \R

Code: Select all

Found_pos_orig := RegExMatch(aFileContents,"`am)^.*(?=: paid the invoice\d+\R^.*\: paid\d+ and on time)", str_purchaser, pos)
I suspect the answer must be easy, but I've searched online for help, maybe I've been unlucky with my searches, but am just getting even more confused by the results
So how can I code for a newline no matter how it got there in the above and for that matter any scenario?

EDIT: ALSO NEED to CHECK for end of file. As just noticed in a test, it won't match unless there are blank lines at end of the file.
Thanks for any help.
User avatar
mikeyww
Posts: 26588
Joined: 09 Sep 2014, 18:38

Re: new line and regex

Post by mikeyww » 24 Jul 2021, 22:37

If you are reading a Windows text file, it would often have a \r\n (CRLF) sequence at the end of a line, so that is how the \R can help, since \R means "any single newline of any type". \Z matches the end of the string.

Code: Select all

RegExMatch("abc", "c\Z", match)
MsgBox,, Match, %match%
I recommend that you post examples of all possible formats of your input, as well as the corresponding desired output, if you need additional feedback about how to fix your code. Without knowing this, I think it would be difficult to revise the code.
bazkeys
Posts: 98
Joined: 20 Jan 2021, 21:58

Re: new line and regex

Post by bazkeys » 25 Jul 2021, 20:00

@mikeyww
Thanks for clarifying that, the \R does seem to do the trick except if it comes to the end of the file and there's no new line then, but it's enough for me to work with for now. :)
User avatar
mikeyww
Posts: 26588
Joined: 09 Sep 2014, 18:38

Re: new line and regex

Post by mikeyww » 25 Jul 2021, 20:28

You can always check for either delimiter.

Code: Select all

str =
(
a
b
c
)
RegExMatch(str, "b(\R|\Z)", match)
MsgBox, 64, Match, %match%
RegExMatch(str, "c(\R|\Z)", match)
MsgBox, 64, Match, %match%
Or:

Code: Select all

str =
(
a
b
c
)
RegExMatch(str, "m`a)b$", match)
MsgBox, 64, Match, %match%
RegExMatch(str, "m`a)c$", match)
MsgBox, 64, Match, %match%
bazkeys
Posts: 98
Joined: 20 Jan 2021, 21:58

Re: new line and regex

Post by bazkeys » 25 Jul 2021, 20:39

@mikeyww

Thanks once again.
Post Reply

Return to “Ask for Help (v1)”