如何替换字符串中除一组子字符串外的所有内容?

时间:2019-11-15 14:42:38

标签: regex ruby gsub

我正在尝试替换input字符串中不是/str|con|dex|wis|int|cha/的所有内容,但是我不确定语法是否正确。我尝试了以下方法:

input.gsub(/[^str|con|dex|wis|int|cha]/, '')
input.gsub(/[^str,con,dex,wis,int,cha]/, '')
input.gsub(/[^str|^con|^dex|^wis|^int|^cha]/, '')
input.gsub(/[^str,^con,^dex,^wis,^int,^cha]/, '')

以下input s:

+4cha
+2 strength
-3wisdom
+1asdfdexasdf

应返回:

cha
str
wis
dex

要清楚,我只希望在input中出现一个子字符串。

4 个答案:

答案 0 :(得分:3)

如果只希望发生一次,则可以使用String#[]方法:

                    count  mean   std   min    25%  50%    75%    max    
    Class  EL_base 
     PC1     0       8   247.04  8.16 236.90 244.15 245.17 247.71 265.41
             1       8   243.25  2.96 237.22 242.57 243.84 244.49 247.29
     PC2     0       8   243.25  2.96 237.22 242.57 243.84 244.49 247.29
             1       8   518.96  6.35 507.27 515.38 519.72 523.65 526.25
             2       8   519.52  2.84 513.77 518.17 520.50 521.46 522.39

这将为您提供第一个匹配项,如果不匹配则为>>> import numpy as np, pandas as pd; np.random.seed(0) >>> import seaborn as sns; sns.set(style="white", color_codes=True) >>> tips = sns.load_dataset("tips") >>> g = sns.jointplot(x="total_bill", y="tip", data=tips) 。如果您想要一个默认的空字符串,只需将其更改为:

input = input[/str|con|dex|wis|int|cha/]

答案 1 :(得分:1)

您不必匹配不是正则表达式的所有内容。您需要匹配所有

inputs = [
  "+4cha",
  "+2 strength",
  "-3wisdom",
  "+1asdfdexasdf",
]
inputs.map do |input|
  matches = input.match(/str|con|dex|wis|int|cha/)
  matches[0] if matches
end.compact
# => ["cha", "str", "wis", "dex"]

因此,给定输入字符串,您将检查它是否与str,con,dex,wis,int或cha中的任何一个匹配。如果是,则返回匹配项。如果不是,则返回nil。

然后,compact从数组中删除所有nil。留下一系列的匹配项。

答案 2 :(得分:1)

您可以https://regex101.com/r/bFwkIZ/1进行此正则表达式,仅获取匹配的第一个组。

re = /(?:.*?)(str|con|dex|wis|int|cha)(?:.*?)/m
str = '+4cha
+2 strength
-3wisdom
+1asdfdexasdf'

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

答案 3 :(得分:1)

来自comment

>> '+4cha'.gsub(/(str|con|dex|wis|int|cha)|./, '\1')
=> "cha"
>> '+2 strength'.gsub(/(str|con|dex|wis|int|cha)|./, '\1')
=> "str"
>> '-3wisdom'.gsub(/(str|con|dex|wis|int|cha)|./, '\1')
=> "wis"
>> '+1asdfdexasdf'.gsub(/(str|con|dex|wis|int|cha)|./, '\1')
=> "dex"

当同一索引中有两个或多个交替时,优先级按声明的顺序从左到右。因此,只要上面的捕获组匹配,左交替就会获胜,并且字符串将通过反向引用得到保留。如果捕获组不匹配,则.将匹配,\1将为空。