2012-01-12 132 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 

不知道你的确切输入格式(换行符或不换行符),以及你想如何输出它,但我希望这有助于。

是的,这可以做得更简洁,但为了清晰起见,我把它分成多行和多个方法。

相关问题