开发者

Regex to leave desired string remaining and others removed

开发者 https://www.devze.com 2023-02-07 16:27 出处:网络
In Ruby, what regex will strip out all but a desired string if present in the开发者_如何转开发 containing string? I know about /[^abc]/ for characters, but what about strings?

In Ruby, what regex will strip out all but a desired string if present in the开发者_如何转开发 containing string? I know about /[^abc]/ for characters, but what about strings?

Say I have the string "group=4&type_ids[]=2&type_ids[]=7&saved=1" and want to retain the pattern group=\d, if it is present in the string using only a regex?

Currently, I am splitting on & and then doing a select with matching condition =~ /group=\d/ on the resulting enumerable collection. It works fine, but I'd like to know the regex to do this more directly.


Simply:
part = str[/group=\d+/]

If you want only the numbers, then:
group_str = str[/group=(\d+)/,1]

If you want only the numbers as an integer, then:
group_num = str[/group=(\d+)/,1].to_i

Warning: String#[] will return nil if no match occurs, and blindly calling nil.to_i always returns 0.


You can try:

$str =~ s/.*(group=\d+).*/\1/;


Typically I wouldn't really worry too much about a complex regex. Simply break the string down into smaller parts and it becomes easier:

asdf = "group=4&type_ids[]=2&type_ids[]=7&saved=1"

asdf.split('&').select{ |q| q['group'] } # => ["group=4"]

Otherwise, you can use regex a bunch of different ways. Here's two ways I tend to use:

asdf.scan(/group=\d+/) # => ["group=4"]
asdf[/(group=\d+)/, 1] # => "group=4"


Try:

str.match(/group=\d+/)[0]
0

精彩评论

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