开发者

ruby regex to extract two parts: digits, then whatever comes after

开发者 https://www.devze.com 2023-03-30 08:22 出处:网络
My user input is a string I need to split into two parts, (1) a partial phone number [any sequence of digits - . space, parens so I assume that is represented by /[\\d\\. \\-\\(\\)]/ ] and (2) whateve

My user input is a string I need to split into two parts, (1) a partial phone number [any sequence of digits - . space, parens so I assume that is represented by /[\d\. \-\(\)]/ ] and (2) whatever follows (if anything).

For example

"开发者_如何学Python88 comment" -> "88" & "comment"
"415-915 second part" --> "415-915" & "second part"
"(415) 915 part 2" --> "(415) 915" & "part 2"
"a note" --> "" & "a note"
"part 2" --> "" & "part 2"

As a relative newbie to ruby and regex, I have no idea how to extract multiple parts, and how to define the second part as being whatever comes after the first part (which basically means whatever comes after anything that doesn't match the first part)


Here's the regex (I'll explain below):

/^([-\d. ()]*)(.*)$/

^ means "start at the beginning of the string"

In ([-\d. ()]*), the * means "match any number of the previous character, and the parens mean to create a match group (this is how you will get the value later). So this is the first sequence.

In (.*), . means "match any single character", so .* means "match any number of any characters", it's basically a catch-all. The parens create a second match group.

$ means "finish at the end of the string"

So in ruby:

string =~ /^([-\d. ()]*)(.*)$/
puts $1.strip # is the phone number (with excess whitespace removed)
puts $2.strip # is the rest (with excess whitespace removed)


Try /([\d.\s()/-]*)(.+)/ The first group will capture the number, the second one the "other" part. I don't know ruby, so you have to implement that pattern yourself.

0

精彩评论

暂无评论...
验证码 换一张
取 消