我怎么能使用gsub使用正则表达式ruby替换为10组?

时间:2017-09-16 04:53:27

标签: ruby regex regex-group

我尝试使用组10替换gsub替换字符串,而不是将此ruby替换为组1和0 我在gsub替换中使用它

CREATE PROCEDURE [uspGetBestDiscount]
(
    ...
    ...
    ...
    @TotalSpend FLOAT = 0,
    @OrderDate DATETIME = NULL,     --NULL to use today date.
    @DiscountRate FLOAT = NULL OUT,
    @DiscountId INT = NULL OUT
)
AS
BEGIN
    IF (@OrderDate IS NULL) SET @OrderDate = GETDATE();
    DECLARE @OrderTime TIME = CAST(@OrderDate AS TIME)

    SET @DiscountId = NULL; SET @DiscountRate = NULL;
    SELECT TOP 1 @DiscountId = [DiscountId], @DiscountRate = [DiscountRate] 
    FROM [tblDiscount]
    WHERE (@TotalSpend >= [MinSpend]) AND
          (@OrderTime >= CAST([StartTime] AS TIME)) AND
          (@OrderTime <= CAST([EndTime] AS TIME)) AND
          ...
          ...
          ...
    ORDER BY [DiscountRate] DESC;
END;

替换并获取组1和字符串“0xp”

我如何解决这个问题

请帮帮我

2 个答案:

答案 0 :(得分:2)

不确定如何引用双位数捕获组,但您始终可以使用以下内容引用名称:

"smnm nmnmn nmnmn dsdsf sffddf sffdfd dfsff fdsdsfd fsdds ssfsff".
  gsub(/(\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (\S+) (?<ten>\S+)/,
       '\k<ten>xp')
# "ssfsffxp"

答案 1 :(得分:2)

没有一个已知的正则表达式引擎支持[0..9]区域之外的未命名组。请改用named_captures,或使用未捕获的群组(?:...),或使用更智能的正则表达式:

"smnm nmnmn nmnmn dsdsf sffddf sffdfd dfsff fdsdsfd fsdds ssfsff".
  gsub(/((?:\S+\s+){9})(\S+)/, "\\1 \\2xp")

#                      ⇑ second group
#                  ⇑⇑⇑ nine times
#        ⇑⇑⇑ don’t capture this!
#       ⇑ first group