簡體   English   中英

Python從積極的眼光中獲取分組值

[英]Python getting the grouped values from positive look ahead

對於以下正則表達式和輸入,我能夠獲得group(1)匹配對象。但是如何從正向獲取匹配對象呢?

正則表達式和輸入

正則表達式為:(\\ w +)(?= \\ s *()|(?:(?<=,|())\\ s *(\\ w +)\\ s *(?:\\ s *(\\ w +)\\ s *)?

輸入為:PRIMARY INDEX FIRST_ONE(PLATFORM_CD,SYSTEM_NAME,DB_NAME,TABLE_NAME,COLUMN_NAME);

在這種情況下,我可以獲取索引名稱“ FIRST_ONE”。 我還需要獲取列名。該怎么做?

我試圖讓組(2),但返回無

我嘗試的代碼是:

upiOrPiValue = re.search(r'(\w+)(?=\s*\()|(?:(?<=,|\())\s*(\w+)\s*(?:\s*(\w+)\s*)?',line)
                print('line : ',line)
                #print('---->',upiOrPiValue)
                if upiOrPiValue == None:
                    pass
                else:
                    PiorUpiName = upiOrPiValue.group(1)
                    print('PiorUpiName : ',PiorUpiName)
                    print('upiOrPiValue.group(2) : ',upiOrPiValue.group(2))

upiOrPiValue.group(1)返回“ FIRST_ONE”值。如何獲取列名?

您的第一個語句如何從正面看待匹配對象 ,后面的語句有點令人困惑。 假設您要捕獲索引名FIRST_ONE和其余的列名PLATFORM_CD ,SYSTEM_NAME ,DB_NAME ,TABLE_NAME ,COLUMN_NAME ,則可以簡化正則表達式,並使用它來捕獲所需的全部內容。

(?:\w+)(?=\s*(?:\(|,|\)))

同樣的Python代碼,

import re
line = 'PRIMARY INDEX FIRST_ONE ( PLATFORM_CD ,SYSTEM_NAME ,DB_NAME ,TABLE_NAME ,COLUMN_NAME );'
arr = re.findall(r'(?:\w+)(?=\s*(?:\(|,|\)))', line)
print(arr)

哪個打印,

['FIRST_ONE', 'PLATFORM_CD', 'SYSTEM_NAME', 'DB_NAME', 'TABLE_NAME', 'COLUMN_NAME']

讓我知道這是否是您想要的。 否則,請更新您的帖子以闡明您的需求。

得到了正則表達式的答案:(\\ w +)(?= \\ s *()|(?:(?<=,|())\\ s *(\\ w +)\\ s *(?:\\ s *(\\ W +)\\ S *)?

# -*- coding: utf-8 -*-

import re

regex = r"(\w+)(?=\s*\()|(?:(?<=,|\())\s*(\w+)\s*(?:\s*(\w+)\s*)?"
strVal = "PRIMARY INDEX FIRST_ONE ( PLATFORM_CD ,SYSTEM_NAME ,DB_NAME ,TABLE_NAME ,COLUMN_NAME );"

matches = re.finditer(regex, strVal)

for match in matches:
    for gCount in range(1, len(match.groups())+1):
        if match.group(gCount) != None:        
            print(match.group(gCount))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM