懒惰分组后的正则表达式匹配字符

时间:2019-08-07 01:48:02

标签: regex

我要在两个组(AS)和(。*?)后专门匹配逗号“,”。 我有一个积极的眼光,可以跳过AS,但无法分组以跳过通配符惰性组。

正则表达式:

(?<= AS)(.*?)(,)

示例文字

    SELECT     LEFT(CustomerCode, 5) AS SMSiteCode, SUBSTRING(CustomerCode, 6, LEN(CustomerCode) - 5) AS SMCustCode, SUBSTRING(AgreeNo, 6, LEN(AgreeNo) - 5) 
                  AS SMAgreeNo, CAST(SeqNo AS int) AS SeqNo, SUBSTRING(TrxDate, 7, 2) + SUBSTRING(TrxDate, 4, 2) + SUBSTRING(TrxDate, 1, 2) AS TrxDate, TrxTime, 
                  CAST(Charge AS bit) AS Charge, CASE WHEN LEN(AnalysisCode) > 5 THEN SUBSTRING(AnalysisCode, 6, LEN(AnalysisCode) - 5) 
                  ELSE AnalysisCode END AS AnalysisCode, CAST(ISNULL(Description, N'') AS nvarchar(100)) AS Description, CAST(TaxAmt AS money) AS TaxAmt, 
                  CAST(TotAmt AS money) AS TotAmt, CAST(Match AS bigint) AS Match, CAST(Confirmed AS bit) AS Confirmed, CAST(Balance AS money) AS Balance, 
                  CAST(QtyBal AS money) AS QtyBal, CAST(ISNULL(Drawer, N'') AS nvarchar(50)) AS Drawer, SUBSTRING(DateBanked, 7, 2) + SUBSTRING(DateBanked, 4, 2) 
                  + SUBSTRING(DateBanked, 1, 2) AS DateBanked, CAST(ISNULL(BankBranch, N'') AS nvarchar(50)) AS BankBranch, CAST(Qty AS float) AS Qty, CAST(ISNULL(Narration, 
                  N'') AS nvarchar(100)) AS Narration, SUBSTRING(DateFrom, 7, 2) + SUBSTRING(DateFrom, 4, 2) + SUBSTRING(DateFrom, 1, 2) AS DateFrom, SUBSTRING(DateTo, 7, 2) 
                  + SUBSTRING(DateTo, 4, 2) + SUBSTRING(DateTo, 1, 2) AS DateTo, CAST(PrintNarration AS bit) AS PrintNarration, CAST(DiscAmt AS float) AS DiscAmt, 
                  CAST(ISNULL(CCAuthNo, N'') AS nvarchar(20)) AS CCAuthNo, CAST(ISNULL(CCTransID, N'') AS nvarchar(20)) AS CCTransID, CAST(UserLogin AS nvarchar(20)) 
                  AS UserLogin, CAST(Reconciled AS bit) AS Reconciled, SUBSTRING(DateReconciled, 7, 2) + SUBSTRING(DateReconciled, 4, 2) + SUBSTRING(DateReconciled, 1, 2) 
                  AS DateReconciled, CAST(PrimaryKey AS bigint) AS PrimaryKey, SUBSTRING(InvDate, 7, 2) + SUBSTRING(InvDate, 4, 2) + SUBSTRING(InvDate, 1, 2) AS InvDate, 
                  CAST(InvNo AS int) AS InvNo FROM         SomeDatabase.dbo.tblTransaction WHERE IsDate(trxTime) = 1

3 个答案:

答案 0 :(得分:1)

您可以尝试\K,但请确保将RegExr中的Javescript从屏幕右上方更改为PCRE

enter image description here

\K定义为:

  

将正则表达式中的给定位置设置为匹配的新“开始”。这意味着在K之前的任何内容都不会在整个比赛中被捕获。

使用\K,您可以尝试执行以下操作:

(?<= AS).*?\K(,)

示例:https://regex101.com/r/X3AdbH/1/

答案 1 :(得分:1)

如果支持\K,则可以通过匹配 AS 并使用negated character class来匹配除逗号以外的任何字符,而无需使用后向和捕获组来进行匹配。

 AS [^,]+\K,

说明

  • AS 匹配空间,AS和空间
  • [^,]+匹配除逗号以外的任意字符1倍以上
  • \K,忘记匹配的内容并匹配逗号

Regex demo

答案 2 :(得分:0)

我猜测您的表达很好,您可能希望将第一个捕获组限制为某些特定字符,如果您愿意,可能看起来像:

(?<= AS)([A-Za-z\d\s]+)(,)

该表达式在regex101.com的右上角进行了解释,如果您想探索/简化/修改它,在this link中,您可以观察到它如何与某些示例输入匹配,如果愿意的话。