regex matching a state in a string

Discussion in 'Ruby' started by Jedrin, Mar 15, 2012.

  1. Jedrin

    Jedrin Guest

    I wonder if there is an easier way to do this. State here is going
    to be two characters,
    it can be preceded by space, or comma and followed by period, end of
    string, or space.
    Also, if this can be done with an SQL select like pattern please let
    me know

    pat = /\s{state.to_s.upcase}\s/
    pat2 = /\s{state.to_s.upcase}$/
    pat3 = /,{state.to_s.upcase}$/
    pat4 = /,{state.to_s.upcase}\s/
    pat5 = /,{state.to_s.upcase}\./
    pat6 = /\s{state.to_s.upcase}\./

    if pat.match(station.description) or
    pat2.match(station.description) or
    pat3.match(station.description) or
    pat4.match(station.description) or
    pat5.match(station.description) or
    Jedrin, Mar 15, 2012
    1. Advertisements

  2. Jedrin

    mars.90226 Guest

    Jedrinæ–¼ 2012å¹´3月16日星期五UTC+8上åˆ5時29分39秒寫é“:
    I think this would help:

    pat = /(\s|,)#{state.to_s.upcase}(\s|\.|$)/

    if station.description =~ pat
    mars.90226, Mar 16, 2012
    1. Advertisements

  3. Why not just

    if /\b#{state.to_s.upcase}\b/ =~ station.description

    \b matches a word boundary which will match at beginning and end of string as well as transitions between punctuation or whitespace and word characters.

    Kind regards

    Robert Klemme, Mar 26, 2012
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.