简体   繁体   中英

Scan String with Ruby Regular Expression

I am attempting to scan the following string with the following regular expression:

 text = %q{akdce ALASKA DISTRICT COURT CM/ECFalmdce 
           ALABAMA MIDDLE DISTRICT COURTalndce
          }

 p courts = text.scan(/(ECF\w+)|(COURT\w+)/)

Ideally, what I want to do is scan the text and pull the text 'ECFalmdce' and 'COURTalndce' With the regex I am using, I am trying to say I want a string that starts with either COURT or ECF followed by a random string of characters.

The array being returned is:

 [["ECFalmdce", nil], [nil, "COURTalndce"]]

What is the deal with the nil's, does anyone have a more efficient way of writing the regex, and does anyone have a link to further documentation on match groups?

Your regex captures differently for ECF and COURT . You can create non-capture groups with ?:

text.scan(/(?:ECF|COURT)\w+/)
# => ["ECFalmdce", "COURTalndce"]

Edit

About non-capture groups: You can use them to create patterns using parenthesis without capturing the pattern.

They're patterns such as (?:pattern)

You can find more information on regular expressions at http://www.regular-expressions.info/refadv.html

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