简体   繁体   中英

Regex multiline match

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:

A valid example (all lines are valid):

something:1
other:2    
more:3     

An invalid example (lines 2,3,4 are invalid -> only lines 1, 5 are valid):

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?

lines will split a string into lines.
any? will return false if the block returns false for any elements.

regex = /^\w+\:\d+$/ 
example_string.lines.any?{|e| e =~ regex }

For a whole-string regex, you can use

regex = /\A(\w+:\d+\s*\n?)+\z/

A simple solution

!!string.match(regex)

The !! forces the answer to a boolean true or false .

Implementing your pseudocode exactly

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM