您的位置:首页 > 其它

两个使用正则表达式来获取字符串中特定子串的方法

2010-03-26 10:51 225 查看
原创文章,转载请注明出处,谢谢!

作者:清林,博客名:飞空静渡

前言:
获取字符串中的字串的方法有很多,这里介绍的是使用正则表达式来获得,都是使用c++的代码。

第一个是使用c中的正则表达式的api。

下面是使用c的api来完成的函数的代码:

std::string regexp_label( const std::string & text,
const std::string & regular_sub_expression )
{
//Extract text from a regular sub-expression.  E.g., "text we don't want (text we want)"
std::string label = "";
regex_t    preg ;
int        nmatch = 2 ;
regmatch_t pmatch[  2 ] ;
int rc = regcomp( &preg, regular_sub_expression .c_str(), REG_EXTENDED | REG_ICASE | REG_NEWLINE ) ;
if (   ( rc == 0 ) //Reg compile OK
&& ( regexec( &preg, text .c_str(), nmatch, pmatch, 0 ) == 0 ) //Match found
)
{
label = text .substr( pmatch[1].rm_so, pmatch[1].rm_eo - pmatch[1].rm_so ) ;
}
return label ;
}


其中regcomp,regexec都是c下面的函数。

下面举个例子来说明怎么使用这个函数。

在linux的/proc目录下有个有关分区信息的文件/proc/partitions,它里面的内容如下(在我们的电脑里,其他人的会略有不同):

major minor #blocks name

8 0 244198584 sda

8 1 29527438 sda1

8 2 1 sda2

8 5 59038843 sda5

8 6 118093783 sda6

8 7 10000431 sda7

8 8 497983 sda8

8 9 27037363 sda9

8 16 156290904 sdb

8 17 53761491 sdb1

8 18 102518797 sdb2

8 32 156290904 sdc

8 33 156288000 sdc1

8 48 156290904 sdd

8 49 313236 sdd1

8 50 3068415 sdd2

现在我们要做的是找出所有的硬盘设备名,如上面的sda,sdb,sdc和sdd,那么这个该怎么做了,看下面的代码。

std::ifstream proc_partitions( "/proc/partitions" ) ;
if ( proc_partitions )
{
//parse device names from /proc/partitions
std::string line ;
std::string device ;
while ( getline( proc_partitions, line ) )
{
device = regexp_label(line, "^[/t ]+[0-9]+[/t ]+[0-9]+[/t ]+[0-9]+[/t ]+([^0-9]+)$") ;
cout<<"find a device:"<<device<<endl;
}
}


现在说的另外一种方法是使用QT的正则表达式的方法,看下QT下是怎么使用,同样是处理上面的/proc/partitions文件,找出硬盘设备名。

QFile partitions("/proc/partitions");
if (partitions.open(QIODevice::ReadOnly))
{
QRegExp rxLine("//s*(//d+)//s+(//d+)//s+(//d+)//s([^0-9]+)//s+");
QByteArray line;

while (!(line = partitions.readLine()).isEmpty())
{
if (rxLine.indexIn(line) != -1)
{
cout<<"find a device:"<<rxLine.cap(4)<<endl;
}
}
}


关于正则表达式和c和QT的正则表达式的api的用法可以google一下,这里不作介绍了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: