I have a string that contains arbitrary number of "\\n"
. I need to know whether there is a line in the string that does not match a certain pattern. If all lines match the pattern, the return should be true
. If not, the return should be false
. The pattern is: word, colon, and digits ( /[\\w]+\\:[\\d]+/
). The code should be in ruby.
These examples are entered by the user in a textarea box on a webpage. Examples of input content are:
something:1
other:2
more:3
something:1
other:stuff
invalid
)/&invalid again
valid_again:4
These examples are received in-code as a single string, lines separated by \\n
(from valid example):
valid_example_string = "something:1\nother:2\nmore:3"
Is there a simple regex way to do this? I am not looking on how to loop through the lines. I am looking for a shorthand regex way (if it's possible) to match the example, something in the lines of (pseudocode):
valid_example_string.test(/the_needed_regex/) # => true
invalid_example_string.test(/the_needed_regex/) # => false
What's the most simple/elegant/efficient way to do this?
For a whole-string regex, you can use
regex = /\A(\w+:\d+\s*\n?)+\z/
!!string.match(regex)
The !!
forces the answer to a boolean true
or false
.
You can monkey-patch the String class to add your test
method:
class String
def test(regex)
!!self.match(regex)
end
end
Output:
valid_example_string.test(regex) # => true
invalid_example_string.test(regex) # => false
regexp = %r{\A(\w+:\d+\n?)*\z} # or %r{\A(\w+:\d+\n?)+\z} to fail on empty strings
valid_example =~ regexp # => 0
invalid_example =~ regexp # => nil
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.