简体   繁体   中英

Regular expression to match numeric strings and newlines in ruby

I've been trying to write a regular expression that matches numeric string and newlines like:

"47832748973284793\r\n321321321321\r\n423423432432423432".match(/\A[+-]?\d+?(_?\d+)*(\.\d+e?\d*)?\Z/) == nil ? false : true 

it will return false because of '\\r\\n', in fact, it should match '\\r\\n' as well.

can someone help me to achieve it ?

So your pattern defines a single number, then you have to add the "special case" as following group but additionally with the the part that differs from the original pattern, the \\r\\n

"47832748973284793\r\n321321321321\r\n423423432432423432".match(/\A[+-]?\d+?(_?\d+)*(\.\d+e?\d*)?(\r\n[+-]?\d+?(_?\d+)*(\.\d+e?\d*)?)*\Z/) == nil ? false : true
                                                                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

and let that special part repeat 0 or more times.

prints out:

irb(main):005:0> text  
=> "47832748973284793\r\n321321321321\r\n423423432432423432"  
irb(main):007:0> text.match(/\A[+-]?\d+?(_?\d+)*(\.\d+e?\d*)?(\r\n[+-]?\d+?(_?\d+)*(\.\d+e?\d*)?)*\Z/) == nil ? false : true  
=> true

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