2

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

what are non-capture groups?
Don't capture the whole pattern. Using /(?:ECF|COURT)\w+/ instead will avoid creating the sub-arrays.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.