本文整理汇总了C++中boost::regex类的典型用法代码示例。如果您正苦于以下问题:C++ regex类的具体用法?C++ regex怎么用?C++ regex使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了regex类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。
示例1: main
int main(int argc, const char** argv)
{
try{
e1.assign(expression_text);
e2.assign(pre_expression);
for(int i = 1; i < argc; ++i)
{
std::cout << "Processing file " << argv[i] << std::endl;
std::ifstream fs(argv[i]);
std::string in;
load_file(in, fs);
fs.close();
std::string out_name = std::string(argv[i]) + std::string(".htm");
std::ofstream os(out_name.c_str());
os << header_text;
// strip '<' and '>' first by outputting to a
// temporary string stream
std::ostringstream t(std::ios::out | std::ios::binary);
std::ostream_iterator<char> oi(t);
boost::regex_replace(oi, in.begin(), in.end(), e2, pre_format, boost::match_default | boost::format_all);
// then output to final output stream
// adding syntax highlighting:
std::string s(t.str());
std::ostream_iterator<char> out(os);
boost::regex_replace(out, s.begin(), s.end(), e1, format_string, boost::match_default | boost::format_all);
os << footer_text;
os.close();
}
}
catch(...)
{ return -1; }
return 0;
}
开发者ID:LancelotGHX,项目名称:Simula,代码行数:33,代码来源:regex_replace_example.cpp
示例2: file
//Extracts opcodes out of the client
QStringList OpcodeFinder::ExtractOpcodes(QString path)
{
QStringList opcodes;
QFile file(path);
//Open the file
if(file.open(QIODevice::ReadOnly))
{
//Read the file data and convert it to hex
std::string data = QString(file.readAll().toHex()).toUpper().toAscii().data();
file.close();
if(data.empty())
{
//No data read
QMessageBox::critical(this, "Error", "No data was read from the client.");
}
else
{
//Regex string for locating opcodes
const static boost::regex e("C744240C(?<opcode>....)0000C7442410........E8........8D|8D..24108D..2418....8BCEC7442418(?<opcode>....)0000C744241C........E8|8B4E10C7442410(?<opcode>....)000041C74424..........518BCEE8");
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
std::string::const_iterator start = data.begin();
std::string::const_iterator end = data.end();
try
{
//Search
while(boost::regex_search(start, end, what, e, flags))
{
//Get the opcode
std::string temp = what["opcode"];
//Add it to the list
opcodes.append((temp.substr(2, 2) + temp.substr(0, 2)).c_str());
//Next
start = what[0].second;
flags |= boost::match_prev_avail;
flags |= boost::match_not_bob;
}
}
catch(std::exception & e)
{
//Display error message (regular expression is probably outdated for this client)
QMessageBox::critical(this, "Error", e.what());
}
}
}
else
{
//File open error
QMessageBox::critical(this, "Error", QString("Unable to open %0 for reading. Could not extract opcodes.").arg(path));
}
return opcodes;
}
开发者ID:ProjectHax,项目名称:OpcodeFinder,代码行数:61,代码来源:opcodefinder.cpp
示例3: stringToList
/**
* Generic tokenizer.
* Splits source into tokens and tries to lexically cast them to TARGET.
* If that fails, boost::bad_lexical_cast is thrown.
* \param source the source string to be split up
* \param separator regular expression to delimit the tokens (defaults to \\s+)
* \param prefix regular expression for text to be removed from the string before it is split up
* ("^" if not given, will be added at the beginning)
* \param postfix regular expression for text to be removed from the string before it is split up
* ("$" if not given, will be added at the end)
* \returns a list of the casted tokens
*/
template<typename TARGET> std::list<TARGET> stringToList(
std::string source, const boost::regex &separator,
boost::regex prefix, boost::regex postfix )
{
std::list<TARGET> ret;
assert( ! separator.empty() );
if ( ! prefix.empty() ) {
if ( prefix.str()[0] != '^' )
prefix = boost::regex( std::string( "^" ) + prefix.str(), prefix.flags() );
source = boost::regex_replace( source, prefix, "", boost::format_first_only | boost::match_default );
}
if ( ! postfix.empty() ) {
if ( postfix.str()[postfix.size() - 1] != '$' )
postfix = boost::regex( postfix.str() + "$", postfix.flags() );
source = boost::regex_replace( source, postfix, "", boost::format_first_only | boost::match_default );
}
boost::sregex_token_iterator i = boost::make_regex_token_iterator( source, separator, -1 );
const boost::sregex_token_iterator token_end;
while ( i != token_end ) {
ret.push_back( boost::lexical_cast<TARGET>( ( i++ )->str() ) );
}
return ret;
}
开发者ID:Rollmops,项目名称:isis,代码行数:42,代码来源:common.hpp
示例4: operator
bool operator()(boost::regex& r) const {
try {
if (wildCard) {
r.assign(AirUtil::regexEscape(pattern, true), boost::regex::icase);
} else {
r.assign(pattern);
}
return true;
} catch(const std::runtime_error&) {
LogManager::getInstance()->message(STRING_F(INVALID_PATTERN, pattern), LogManager::LOG_ERROR);
return false;
}
}
开发者ID:egoitzro,项目名称:airdcnano,代码行数:13,代码来源:StringMatch.cpp
示例5: TRC_DEBUG
bool EnumService::parse_regex_replace(const std::string& regex_replace, boost::regex& regex, std::string& replace)
{
bool success = false;
// Split the regular expression into the match and replace sections. RFC3402
// says any character other than 1-9 or i can be the delimiter, but
// recommends / or !. We just use the first character and reject if it
// doesn't neatly split the regex into two.
std::vector<std::string> match_replace;
Utils::split_string(regex_replace, regex_replace[0], match_replace);
if (match_replace.size() == 2)
{
TRC_DEBUG("Split regex into match=%s, replace=%s", match_replace[0].c_str(), match_replace[1].c_str());
try
{
regex.assign(match_replace[0], boost::regex::extended);
replace = match_replace[1];
success = true;
}
catch (...)
{
success = false;
}
}
else
{
success = false;
}
return success;
}
开发者ID:AiprNick,项目名称:sprout,代码行数:32,代码来源:enumservice.cpp
示例6: DebugOut
void Location::parseGprmc(string gprmc)
{
DebugOut(7)<<"parsing gprmc message"<<endl;
regularExpression.assign(gprmcRegEx);
boost::smatch tokens;
if (boost::regex_match (gprmc, tokens, regularExpression) )
{
if(tokens[4] == "A")
{
isActive = true;
}
int i=0;
for(auto tok : tokens)
{
DebugOut(0)<<i++<<":"<<tok<<endl;
}
parseTime(tokens[1],tokens[2],tokens[3],tokens[13],tokens[14],tokens[15]);
parseLatitude(tokens[5], tokens[6], tokens[7]);
parseLongitude(tokens[8], tokens[9], tokens[10]);
parseSpeed(tokens[11]);
parseDirection(tokens[12]);
}
}
开发者ID:timkoma,项目名称:automotive-message-broker,代码行数:32,代码来源:gpsnmea.cpp
示例7: main
int
main (int argc, const char *argv[])
{
Filesystem::convert_native_arguments (argc, (const char **)argv);
ArgParse ap;
ap.options ("iinfo -- print information about images\n"
OIIO_INTRO_STRING "\n"
"Usage: iinfo [options] filename...",
"%*", parse_files, "",
"--help", &help, "Print help message",
"-v", &verbose, "Verbose output",
"-m %s", &metamatch, "Metadata names to print (default: all)",
"-f", &filenameprefix, "Prefix each line with the filename",
"-s", &sum, "Sum the image sizes",
"-a", &subimages, "Print info about all subimages",
"--hash", &compute_sha1, "Print SHA-1 hash of pixel values",
"--stats", &compute_stats, "Print image pixel statistics (data window)",
NULL);
if (ap.parse(argc, argv) < 0 || filenames.empty()) {
std::cerr << ap.geterror() << std::endl;
ap.usage ();
return EXIT_FAILURE;
}
if (help) {
ap.usage ();
exit (EXIT_FAILURE);
}
if (! metamatch.empty())
field_re.assign (metamatch,
boost::regex::extended | boost::regex_constants::icase);
// Find the longest filename
size_t longestname = 0;
BOOST_FOREACH (const std::string &s, filenames)
longestname = std::max (longestname, s.length());
longestname = std::min (longestname, (size_t)40);
long long totalsize = 0;
BOOST_FOREACH (const std::string &s, filenames) {
ImageInput *in = ImageInput::open (s.c_str());
if (! in) {
std::string err = geterror();
if (err.empty())
err = Strutil::format ("Could not open \"%s\"", s.c_str());
std::cerr << "iinfo: " << err << "\n";
continue;
}
ImageSpec spec = in->spec();
print_info (s, longestname, in, spec, verbose, sum, totalsize);
in->close ();
delete in;
}
开发者ID:Chifoncake,项目名称:oiio,代码行数:53,代码来源:iinfo.cpp
示例8: GC_TRACE
int ChessEngineGnu::match(const string &str,
boost::regex &re,
vector<string> &matches)
{
boost::cmatch what;
matches.clear();
GC_TRACE("match(): %s\n", re.str().c_str());
if( boost::regex_match(str.c_str(), what, re) )
{
// what[0] is the whole string
for(size_t i=1; i<what.size(); ++i)
{
GC_TRACE(" \"%s\"\n", what[i].str().c_str());
matches.push_back(what[i].str());
}
}
GC_TRACE(" %zu matches\n", matches.size());
return (int)matches.size();
}
开发者ID:roadnarrows-robotics,项目名称:chess_engine,代码行数:24,代码来源:chess_engine_gnu.cpp
示例9: expr
TestCaseReader::TestCaseReader(const boost::filesystem::path & testCaseDir)
{
const boost::regex expr("(\\d{3,4})-(.*)\\.xml");
for (boost::filesystem::directory_iterator it = boost::filesystem::directory_iterator(testCaseDir);
it != boost::filesystem::directory_iterator(); ++it)
{
const boost::filesystem::path path = it->path();
//ignore files that don't end in ".xml"
if (path.extension() != ".xml")
{
continue;
}
#if defined (BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 3
const std::string filename = path.filename().string();
#else
const std::string filename = path.filename();
#endif
boost::smatch matchResults;
if (boost::regex_match(filename,matchResults,expr))
{
//std::wcout << "Found testcase " << matchResults[1].str().c_str() << " brief description '" << matchResults[2].str().c_str()<< "'" << std::endl;
const size_t tc = boost::lexical_cast<size_t>(matchResults[1]);
if (m_testCases.size() < (tc + 1))
{
m_testCases.resize(tc + 1);
}
if (m_testCases[tc] != NULL)
{
std::wcerr << "There appears to be two test cases with number " << tc << std::endl;
exit(1);
}
std::ostringstream xml;
xml << boost::filesystem::ifstream(path).rdbuf();
//std::wcout << "Read xml (" << xml.str().size() << " bytes) '" << xml.str().c_str() << "'" << std::endl;
try
{
m_testCases[tc] = boost::dynamic_pointer_cast<DoseTest::Items::TestCase>
(Safir::Dob::Typesystem::Serialization::ToObject(Safir::Dob::Typesystem::Utilities::ToWstring(xml.str())));
}
catch (const std::exception & exc)
{
std::wcerr << "Failed to read file '" << path.string().c_str() << "' due to exception with message" << std::endl
<<exc.what() << std::endl;
exit(2);
}
}
else
{
std::wcerr << "File '"
<< path.filename().c_str()
<< "' did not match the pattern for test case files: '"
<< expr.str().c_str()
<< "'" << std::endl;
}
}
}
开发者ID:f8industries,项目名称:safir_sdk_core,代码行数:62,代码来源:TestCaseReader.cpp
示例10: write
void write( const string& sourceFilepath,
pwiz::identdata::IdentDataFile::Format outputFormat,
const string& filenameSuffix,
const string& searchEngineName,
const string& searchEngineVersion,
const string& searchEngineURI,
const string& searchDatabase,
boost::regex cleavageAgentRegex,
const string& decoyPrefix,
const RunTimeVariableMap& vars ) const
{
using namespace pwiz::identdata;
namespace msdata = pwiz::msdata;
namespace proteome = pwiz::proteome;
IdentData mzid;
mzid.id = sourceFilepath + " " + searchDatabase + " " + searchEngineName + " " + searchEngineVersion;
mzid.creationDate = GetDateTime();
// add default CVs
mzid.cvs = defaultCVList();
// add the SpectrumIdentificationProtocol
SpectrumIdentificationProtocolPtr sipPtr(new SpectrumIdentificationProtocol("SIP"));
mzid.analysisProtocolCollection.spectrumIdentificationProtocol.push_back(sipPtr);
CVTranslator cvTranslator;
CVID searchEngineCVID = cvTranslator.translate(searchEngineName);
// add analysis software
sipPtr->analysisSoftwarePtr.reset(new AnalysisSoftware("AS"));
mzid.analysisSoftwareList.push_back(sipPtr->analysisSoftwarePtr);
// set software name
if (searchEngineCVID != CVID_Unknown)
sipPtr->analysisSoftwarePtr->softwareName.set(searchEngineCVID);
else
sipPtr->analysisSoftwarePtr->softwareName.set(MS_custom_unreleased_software_tool, searchEngineName);
// set version and URI
sipPtr->analysisSoftwarePtr->version = searchEngineVersion;
sipPtr->analysisSoftwarePtr->URI = searchEngineURI;
// set search type
sipPtr->searchType.cvid = MS_ms_ms_search;
// add a mass table for all MS levels
MassTablePtr massTable(new MassTable("MT"));
massTable->msLevel.push_back(1);
massTable->msLevel.push_back(2);
massTable->msLevel.push_back(3);
sipPtr->massTable.push_back(massTable);
// specify amino acid masses used
const char* residueSymbols = "ACDEFGHIKLMNPQRSTUVWY";
for (int i=0; i < 21; ++i)
{
const AminoAcid::Info::Record& record = AminoAcid::Info::record(residueSymbols[i]);
ResiduePtr rp(new Residue);
rp->code = record.symbol;
rp->mass = record.residueFormula.monoisotopicMass();
massTable->residues.push_back(rp);
}
// add the SpectrumIdentificationList
SpectrumIdentificationListPtr silPtr(new SpectrumIdentificationList("SIL"));
mzid.dataCollection.analysisData.spectrumIdentificationList.push_back(silPtr);
if (vars.count("SearchStats: Overall"))
{
string searchStats = vars.find("SearchStats: Overall")->second;
silPtr->numSequencesSearched = lexical_cast<int>(searchStats.substr(0, searchStats.find_first_of(' ')));
}
// add the SpectrumIdentification
SpectrumIdentificationPtr siPtr(new SpectrumIdentification("SI"));
siPtr->spectrumIdentificationListPtr = silPtr;
siPtr->spectrumIdentificationProtocolPtr = sipPtr;
siPtr->activityDate = mzid.creationDate;
mzid.analysisCollection.spectrumIdentification.push_back(siPtr);
// add search database
SearchDatabasePtr sdb(new SearchDatabase("SDB"));
sdb->fileFormat.cvid = MS_FASTA_format;
sdb->location = searchDatabase;
sdb->name = bfs::path(searchDatabase).filename();
sdb->set(MS_database_type_amino_acid);
sdb->databaseName.userParams.push_back(UserParam("database name", sdb->name, "xsd:string"));
mzid.dataCollection.inputs.searchDatabase.push_back(sdb);
mzid.analysisCollection.spectrumIdentification[0]->searchDatabase.push_back(sdb);
// add source file
SpectraDataPtr spectraData(new SpectraData("SD"));
spectraData->location = sourceFilepath;
spectraData->name = bfs::path(spectraData->location).filename();
mzid.dataCollection.inputs.spectraData.push_back(spectraData);
mzid.analysisCollection.spectrumIdentification[0]->inputSpectra.push_back(spectraData);
// set source file format (required for a semantically valid mzIdentML file)
//.........这里部分代码省略.........
开发者ID:PNNL-Comp-Mass-Spec,项目名称:PeptideListToXML,代码行数:101,代码来源:Proteowizard_Example.cpp
示例11: assert
void bcp_implementation::copy_path(const fs::path& p)
{
assert(!fs::is_directory(m_boost_path / p));
if(fs::exists(m_dest_path / p))
{
std::cout << "Copying (and overwriting) file: " << p.string() << "\n";
fs::remove(m_dest_path / p);
}
else
std::cout << "Copying file: " << p.string() << "\n";
//
// create the path to the new file if it doesn't already exist:
//
create_path(p.branch_path());
//
// do text based copy if requested:
//
if(p.leaf() == "Jamroot")
{
static std::vector<char> v1, v2;
v1.clear();
v2.clear();
std::ifstream is((m_boost_path / p).c_str());
std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));
static boost::regex libname_matcher;
if(libname_matcher.empty())
{
libname_matcher.assign("boost_");
}
regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), libname_matcher, m_namespace_name + "_");
std::swap(v1, v2);
v2.clear();
std::ofstream os;
if(m_unix_lines)
os.open((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
else
os.open((m_dest_path / p).c_str(), std::ios_base::out);
os.write(&*v1.begin(), v1.size());
os.close();
}
else if(m_namespace_name.size() && m_lib_names.size() && is_jam_file(p))
{
static std::vector<char> v1, v2;
v1.clear();
v2.clear();
std::ifstream is((m_boost_path / p).c_str());
std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));
static boost::regex libname_matcher;
if(libname_matcher.empty())
{
std::string re = "\\<";
re += *m_lib_names.begin();
for(std::set<std::string>::const_iterator i = ++m_lib_names.begin(); i != m_lib_names.end(); ++i)
{
re += "|" + *i;
}
re += "\\>";
libname_matcher.assign(re);
}
regex_replace(std::back_inserter(v2), v1.begin(), v1.end(), libname_matcher, get_new_library_name(m_namespace_name));
std::swap(v1, v2);
v2.clear();
std::ofstream os;
if(m_unix_lines)
os.open((m_dest_path / p).c_str(), std::ios_base::binary | std::ios_base::out);
else
os.open((m_dest_path / p).c_str(), std::ios_base::out);
os.write(&*v1.begin(), v1.size());
os.close();
}
else if(m_namespace_name.size() && is_source_file(p))
{
//
// v1 hold the current content, v2 is temp buffer.
// Each time we do a search and replace the new content
// ends up in v2: we then swap v1 and v2, and clear v2.
//
static std::vector<char> v1, v2;
v1.clear();
v2.clear();
std::ifstream is((m_boost_path / p).c_str());
std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), std::back_inserter(v1));
static const boost::regex namespace_matcher(
"(?|"
"(namespace\\s+)boost(_\\w+)?(?:(\\s*::\\s*)phoenix)?"
"|"
"(namespace\\s+)(adstl|phoenix|rapidxml)\\>"
"|"
"()\\<boost((?:_(?!intrusive_tags)\\w+)?\\s*(?:::))(?:(\\s*)phoenix)?"
"|"
"()\\<((?:adstl|phoenix|rapidxml)\\s*(?:::))"
"|"
"(namespace\\s+\\w+\\s*=\\s*(?:::\\s*)?)boost(_\\w+)?(?:(\\s*::\\s*)phoenix)?"
//.........这里部分代码省略.........
开发者ID:AlexanderGarmash,项目名称:boost-ndk,代码行数:101,代码来源:copy_path.cpp
示例12: main
int main(int argc, char * argv[])
{
try{
po::options_description opts("Options");
opts.add_options()
("help,h", "produce help message")
//("after-context,A", po::value<int>(&after_context)->default_value(0), "Print arg lines of trailing context after matching lines. Places a line containing -- between contiguous groups of matches.")
//("before-context,B", po::value<int>(&before_context)->default_value(0), "Print arg lines of leading context before matching lines. Places a line containing -- between contiguous groups of matches.")
//("context,C", po::value<int>(), "Print arg lines of output context. Places a line containing -- between contiguous groups of matches.")
("byte-offset,b", "Print the byte offset within the input file before each line of output.")
("count,c", "Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see below), count non-matching lines.")
("extended-regexp,E", "Interpret PATTERN as an POSIX-extended regular expression.")
("perl-regexp,P", "Interpret PATTERN as a Perl regular expression.")
//("regexp,e", po::value<std::string>(&pattern), "Use PATTERN as the pattern; useful to protect patterns beginning with -.")
("basic-regexp,G", "Interpret arg as a POSIX-basic regular expression (see below). This is the default.")
("ignore-case,i", "Ignore case distinctions in both the PATTERN and the input files.")
("files-without-match,L", "Suppress normal output; instead print the name of each input file from which no output would normally have been printed. The scanning will stop on the first match.")
("files-with-matches,l", "Suppress normal output; instead print the name of each input file from which output would normally have been printed. The scanning will stop on the first match.")
("line-number,n", "Prefix each line of output with the line number within its input file.")
;
// Hidden options, will be allowed both on command line and
// in config file, but will not be shown to the user.
po::options_description hidden("Hidden options");
hidden.add_options()
("input-file", po::value< std::vector<std::string> >(), "input file")
("input-pattern", po::value< std::string >(), "input file")
;
po::options_description cmdline_options;
cmdline_options.add(opts).add(hidden);
po::positional_options_description p;
p.add("input-pattern", 1);
p.add("input-file", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(cmdline_options)/*.options(hidden)*/.positional(p).run(), vm);
po::notify(vm);
if (vm.count("help"))
{
std::cout << opts << "\n";
return 0;
}
if (vm.count("context"))
{
after_context = vm["context"].as< int >();
before_context = after_context;
}
if(vm.count("extended-regexp"))
{
flags = boost::regex_constants::extended;
}
if(vm.count("basic-regexp"))
{
flags = boost::regex_constants::basic;
}
if(vm.count("perl-regexp"))
{
flags = boost::regex_constants::perl;
}
if(vm.count("ignore-case"))
{
flags |= boost::regex_constants::icase;
}
if(vm.count("byte-offset"))
{
print_byte_offset = true;
}
if(vm.count("count"))
{
count_only = true;
}
if(vm.count("files-without-match"))
{
print_non_matching_files = true;
}
if(vm.count("files-with-matches"))
{
files_only = true;
}
if(vm.count("line-number"))
{
print_line_numbers = true;
}
if(vm.count("input-pattern"))
{
pattern = vm["input-pattern"].as< std::string >();
re.assign(pattern, flags);
}
else
{
std::cerr << "No pattern specified" << std::endl;
return 1;
}
if (vm.count("input-file"))
{
const std::vector<std::string>& files = vm["input-file"].as< std::vector<std::string> >();
file_count = files.size();
for(std::vector<std::string>::const_iterator i = files.begin(); i != files.end(); ++i)
//.........这里部分代码省略.........
开发者ID:0xDEC0DE8,项目名称:mcsema,代码行数:101,代码来源:grep.cpp
示例13: mStream
MarkExtracter(std::ostream& inOutStream, const DesignSharedPtr& inDesign,
string inPattern) : mStream(inOutStream), mDesign(inDesign), mPattern(inPattern) {
mStream << "Searching for '" << mPattern << "'" << std::endl;
mStream << "NEAT" << std::endl;
mRegex.assign(mPattern);
}
开发者ID:torc-isi,项目名称:torc,代码行数:6,代码来源:MarkExtracter.hpp
注:本文中的boost::regex类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论