繁体   English   中英

按 Ruby 中的字符集对字符串进行分区/拆分

[英]Partition/split a string by character set in Ruby

如何在我的字符串中分隔不同的字符集? 例如,如果我有这些字符集:

[a-z]
[A-Z]
[0-9]
[\s]
{everything else}

这个输入:

thisISaTEST***1234pie

然后我想分隔不同的字符集,例如,如果我使用换行符作为分隔符:

this
IS
a
TEST
***
1234
pie

我已经尝试过这个正则表达式,并具有积极的前瞻性:

'thisISaTEST***1234pie'.gsub(/(?=[a-z]+|[A-Z]+|[0-9]+|[\s]+)/, "\n")

但显然+ s 并不贪婪,因为我得到:

t
h
# (snip)...
S
T***
1
# (snip)...
e

我剪掉了不相关的部分,但正如你所看到的,每个字符都被算作自己的字符集,除了{everything else}字符集。

我怎样才能做到这一点? 它不一定必须是正则表达式。 将它们拆分成一个数组也可以。

困难的部分是匹配与正则表达式其余部分不匹配的任何内容。 忘记这一点,想办法将不匹配的部分与匹配的部分混合在一起。

"thisISaTEST***1234pie"
.split(/([a-z]+|[A-Z]+|\d+|\s+)/).reject(&:empty?)
# => ["this", "IS", "a", "TEST", "***", "1234", "pie"]

在 ASCII 字符集中,除了字母数字和空格之外,还有 32 个“标点”字符,它们与属性结构\\p{punct}匹配。

要将字符串拆分为单个类别的序列,您可以编写

str = 'thisISaTEST***1234pie'
p str.scan(/\G(?:[a-z]+|[A-Z]+|\d+|\s+|[\p{punct}]+)/)

输出

["this", "IS", "a", "TEST", "***", "1234", "pie"]

或者,如果您的字符串包含 ASCII 集之外的字符,您可以按照属性编写整个内容,如下所示

p str.scan(/\G(?:\p{lower}+|\p{upper}+|\p{digit}+|\p{space}|[^\p{alnum}\p{space}]+)/)

这里有两个解决方案。

String#scan使用正则表达式

str = "thisISa\n TEST*$*1234pie"
r = /[a-z]+|[A-Z]+|\d+|\s+|[^a-zA-Z\d\s]+/
str.scan r
  #=> ["this", "IS", "a", "\n ", "TEST", "*$*", "1234", "pie"]

由于^[^a-zA-Z\\d\\s]的开头,该字符类匹配字母(小写和大写)、数字和空格以外的任何字符。

使用Enumerable#slice_when 1

首先是一个辅助方法:

def type(c)
  case c
  when /[a-z]/ then 0
  when /[A-Z]/ then 1
  when /\d/    then 2
  when /\s/    then 3
  else              4
  end
end

例如,

type "f"   #=> 0
type "P"   #=> 1
type "3"   #=> 2
type "\n"  #=> 3
type "*"   #=> 4    

然后

str.each_char.slice_when { |c1,c2| type(c1) != type(c2) }.map(&:join)
  #=> ["this", "IS", "a", "TEST", "***", "1234", "pie"]

1. slich_when在 Ruby v2.4 中首次亮相。

非单词、非空格字符可以用[^\\w\\s]覆盖,因此:

"thisISaTEST***1234pie".scan /[a-z]+|[A-Z]+|\d+|\s+|[^\w\s]+/
#=> ["this", "IS", "a", "TEST", "***", "1234", "pie"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM