[Solved] Regex bug? Incorrect match with a single newline '\n' character at string's end

Godot Version

3.5.3 and 4.4

Question

Edit: I just checked, the same is happening in Godot 4.4.

Here is the most basic example:

var regex: RegEx = RegEx.new()

func _ready():
	regex.compile("^a*$")
	print(regex.search("aaa"))
	print(regex.search("aaa\n"))
	print(regex.search("aaa\naaa"))
	print(regex.search("\naaa"))
	print(regex.search("aaa\n\n"))

This regex should match any string with arbitrary many ‘a’ characters, and nothing else. Of all the strings checked in _ready() function, regex.search matches “aaa” and “aaa\n”. All others return null. “aaa\n” should also return null. I have an idea of a couple workarounds - for instance, I could just have an additional check to see if a string ends with ‘\n’. However, I’d like to know if there is a correct way of doing this or if I’m missing something obvious.

As far as I know, the $ anchor matches the absolute end of the string OR the position right before a newline at the end of a string, so in most regex engines, saying that “aaa\n” should return null isn’t necessarily a bug, but expected behaviour. But someone should correct me if I’m wrong.

1 Like

Thank you very much for your reply! It seems that it works exactly as you described it. After some searching and testing, \z should probably be used instead of $ to match the end of the string. In the article that led me to that conclusion (it wasn’t a Godot-related article), they said that not every platform supports \z. Some use \Z, and some don’t recognize either. I am on Linux, so if anyone can test that on Windows, it would be much appreciated. The first line in the _ready() function should be replaced with:

regex.compile("^a*\\z")

I believe when they are talking about “platform” they are not talking about the operating system. Godot’s regex should work the same on every OS.

1 Like

I believe that too, but I have seen some really weird software behavior, so I just wanted to verify.

1 Like

\z works as the end of string for me on Windows 11 :+1:

1 Like

Great, thanks!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.