大佬教程收集整理的这篇文章主要介绍了Ruby使用正则表达式从字符串中提取数据,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Sr.No. Course_Code Course_Name Credit Grade Attendance_Grade
我收到的实际字符串具有以下形式
1 CA727 PRINCIPLES OF COMPILER DESIGN 3 A M
我感兴趣的是Course_Code,Course_Name和Grade,在这个例子中,值将是
Course_Code : CA727 Course_Name : PRINCIPLES OF COMPILER DESIGN Grade : A
有一些方法可以使用正则表达式或其他一些技术来轻松地提取此信息,而不是手动解析字符串.
我在1.9模式下使用jruby.
course_line = / ^ # StarTing at the front of the String (?<SrNo>\d+) # Capture one or more digits; call the result "SrNo" \s+ # Eat some whitespace (?<Code>\S+) # Capture all the non-whitespace you can; call it "Code" \s+ # Eat some whitespace (?<Name>.+\S) # Capture as much as you can # (while letTing the rest of the regex still work) # Make sure you end with a non-whitespace character. # Call this "Name" \s+ # Eat some whitespace (?<Credit>\S+) # Capture all the non-whitespace you can; call it "Credit" \s+ # Eat some whitespace (?<Grade>\S+) # Capture all the non-whitespace you can; call it "Grade" \s+ # Eat some whitespace (?<Attendance>\S+) # Capture all the non-whitespace; call it "Attendance" $ # Make sure that we're at the end of the line now /x str = "1 CA727 PRINCIPLES OF COMPILER DESIGN 3 A M" parts = str.match(course_linE) puts " Course Code: #{parts['Code']} Course Name: #{parts['Name']} Grade: #{parts['Grade']}".Strip #=> Course Code: CA727 #=> Course Name: PRINCIPLES OF COMPILER DESIGN #=> Grade: A
以上是大佬教程为你收集整理的Ruby使用正则表达式从字符串中提取数据全部内容,希望文章能够帮你解决Ruby使用正则表达式从字符串中提取数据所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。