I'm parsing a file and want to check if a string contains only white space characters. (Ie, matches the \s symbol in a regex). The RegEx class in godot has search functions, but nothing for checking if the entire string matches a regular expression. Is there a way to do this?
How to check if a string contains only whitespace characters?
- Edited
- Best Answerset by kitfox
kitfox RegEx::search()
returns RegExMatch object which contains the size and content of the match. Compare its length to the length of the original string. The whole string matched the pattern if lengths are equal.
var s = " \t \t\t "
var re = RegEx.new()
re.compile("\\s*")
if s.length() == re.search(s).get_string(0).length():
print("all whitespaces")
- Edited
kitfox checking if the entire string matches a regular expression
You can anchor the regex to the beginning and end of the string. ^ matches the beginning of the string and $ matches the end. This matches a string containing only whitespace:
re.compile("^\\s*$")
Alternatively, you could search for a non-whitespace character. If the string has at least one non-whitespace character, then it's not a string containing only whitespace. Inside brackets, ^ at the beginning negates the following character specification. This matches a non-whitespace character:
re.compile("[^\\s]")
This is equivalent to the previous:
re.compile("\\S")
I haven't verified that all of the above is supported by Godot's Regex class, but I've used some complex regex patterns, and they worked as expected.