2012-01-12 209 views
1

我可以使用RegEx(子字符串insted)來獲取字符串中的字符串嗎?正則表達式在字符串中查找字符串

我希望得到的只是從一系列INSERT語句

INSERT INTO tableA VALUES (col1, col2, col3); 
INSERT INTO tableB VALUES (col1, col2, col3); 
INSERT INTO tableC VALUES (col1, col2, col3); 

的表名使用正則表達式我想獲得(單線,因爲我從文件中讀取):

tableA 
tableB 
tableC 

我試過這個表達式(INTO)([a-z_])*它給了我'INTO tableA',我可以使用SubString或Replace來給我剩下的東西,但我猜這可能是在RegEx中完成的。

+0

你在用什麼語言?從語言到語言,正則表達式的功能有很大的不同。 – 2012-01-12 10:34:02

+0

我正在使用。Net(C#) – Kman 2012-01-12 10:35:32

回答

2

使用這個表達式與回顧後:

(?i)(?<=into\s+)\S+ 

var tables = Regex.Matches(s, @"(?i)(?<=into\s+)\S+") 
    .Cast<Match>().Select(m => m.Value); 
+0

謝謝!奇蹟般有效! – Kman 2012-01-12 10:51:25

+0

@Kman,不客氣。 – 2012-01-12 10:52:13

0

使用文本編輯器和搜索+替換如下:

Find: ^INSERT INTO (.*) VALUES.* 
Replace: \1 

務必檢查Regular Expression選項。

這就是我的記事本++屏幕看起來像和相信我,它已經工作。

enter image description here

0

您可以用括號捕獲匹配的字符串的子字符串:

^ *INSERT\s+INTO\s+(\w+) 

從比賽結果,你可以使用\1$1根據您的語言中提取第一捕獲組。

*\s+將忽略多餘的空格。

0

在PHP

$regex = "/INSERT INTO (.*) VALUES/"; 

在Java

String regex = "INSERT INTO (.*?) VALUES"; 

第一捕獲集團將持有你想要什麼。

1

由於您使用C#,我將指定我會怎麼做,從開始到結束:

 //create regex - the (.*?) is a capture group 
     var regex = new Regex("INSERT INTO (.*?) VALUES"); 

     //mimic text lines read from a file 
     var sqlStrings = new string[] {"INSERT INTO tableA VALUES (col1, col2, col3)", "INSERT INTO tableB VALUES (col1, col2, col3)", "INSERT INTO tableC VALUES (col1, col2, col3)"}; 
     foreach (var line in sqlStrings) 
     { 
      //get the first match with the regex we created 
      var match = regex.Match(line); 

      //print out the first capture group 
      Console.WriteLine(match.Groups[1].ToString()); 
     } 

這將寫出了以下工作:

tableA 
tableB 
tableC 

不知道你的確切輸入格式(換行符或不換行符),以及你想如何輸出它,但我希望這有助於。

是的,這可以做得更簡潔,但爲了清晰起見,我把它分成多行和多個方法。

相關問題