代码之家  ›  专栏  ›  技术社区  ›  Meyssam Toluie

数字的正确模式是什么

  •  1
  • Meyssam Toluie  · 技术社区  · 8 年前

    我正在使用like操作符寻找正确的模式。

    我的代码:

    DECLARE @exp1 varchar(100) = '<<PointBalance , 8>>'
    DECLARE @exp2 varchar(100) = '<<PointBalance , 985>>'    
    IF (TRIM(REPLACE(@exp1, ' ', '')) LIKE '<<PointBalance,[0-9]>>')
        PRINT 'Matched'
    

    正如预期的那样,if语句没有为exp2打印“Matched”。

    位数不相同。我需要一个模式来验证nDigit数字。

    2 回复  |  直到 8 年前
        1
  •  1
  •   HABO    8 年前

    Like 模式不能检查可变长度的数字字符串,但它可以检查子字符串中的任何 数字:

    -- Sample data.
    declare @Samples as Table ( Sample VarChar(32) );
    insert into @Samples ( Sample ) values
      ( '<<PointBalance , 1>>' ), ( '<<PointBalance , 12>>' ), ( '<<PointBalance , 123>>' ),
      ( '<<PointBalance , 1234>>' ), ( '<<PointBalance , 1 3 5>>' ), ( '<<PointBalance , 1J3>>' );
    
    with
      Step1 as (
        select Sample,
          -- Extract the substring starting after the comma and trim leading whitespace.
          LTrim( Substring( Sample, CharIndex( ',', Sample ) + 1, 32 ) ) as AfterComma
          from @Samples ),
      Step2 as (
        select Sample, AfterComma,
          -- Extract the substring prior to the first   '>'   and trim trailing whitespace.
          RTrim( Substring( AfterComma, 1, CharIndex( '>', AfterComma ) - 1 ) ) as TargetString
          from Step1 )
    select *,
      -- Check the remaining string for any characters that are not digits.
      case when TargetString like '%[^0-9]%' then 0 else 1 end as Numeric
      from Step2;
    
        2
  •  1
  •   Yogesh Sharma    8 年前

    例如,我想使用 substring() 具有 patindex() 函数读取数值并比较整个字符串

    DECLARE @exp1 varchar(100) = '<<PointBalance , 811111>>'
    DECLARE @exp2 varchar(100) = '<<PointBalance , 489>>'    
    IF (trim(REPLACE(@exp2, ' ', '')) like '<<PointBalance,'+substring(@exp2, patindex('%[0-9]%', @exp2), len(replace(@exp2, ' ', '')) - patindex('%[0-9]%', replace(@exp2, ' ', ''))-1)+'>>')
    PRINT 'Matched'