Exemple #1
0
QHash<Profile::Property, QVariant> ProfileCommandParser::parse(const QString& input)
{
    QHash<Profile::Property, QVariant> changes;

    // regular expression to parse profile change requests.
    //
    // format: property=value;property=value ...
    //
    // where 'property' is a word consisting only of characters from A-Z
    // where 'value' is any sequence of characters other than a semi-colon
    //
    static QRegExp regExp("([a-zA-Z]+)=([^;]+)");

    int offset = 0;
    while (regExp.indexIn(input, offset) != -1) {
        if (regExp.capturedTexts().count() == 3) {
            Profile::Property property = Profile::lookupByName(
                                             regExp.capturedTexts().at(1));
            const QString value = regExp.capturedTexts().at(2);
            changes.insert(property, value);
        }

        offset = input.indexOf(';', offset) + 1;
        if (offset == 0)
            break;
    }

    return changes;
}
Exemple #2
0
/*!
 * \brief treatFuncs treat the last level of recursion: parenthesis
 * \param expr The expression to parse.
 * \param noProblem A reference to a bool set to true if no problem happened, false otherwise.
 * \return The value of the parsed subexpression or 0 in case of error.
 *
 * The expression should not contain operators not nested anymore. The subexpressions within parenthesis will be treated by recalling the level 1 function.
 */
double treatFuncsInt(QString const& expr, bool & noProblem)
{

    noProblem = true;

    QRegExp funcExpInteger = funcExprInteger;
    QRegExp integerExp = integerExpr;
    QRegExp numberExp = numberExpr;

    if (funcExpInteger.exactMatch(expr.trimmed())) {

        int sign = funcExpInteger.capturedTexts()[1].isEmpty() ? 1 : -1;
        QString subExpr = funcExpInteger.capturedTexts()[2];

        double val = treatLevel1Int(subExpr, noProblem);

        if (!noProblem) {
            return 0;
        }

        return sign*val;

    } else if(numberExp.exactMatch(expr.trimmed())) {
        double value = QVariant(expr).toDouble(&noProblem);
        return value;
    }

    noProblem = false;
    return 0;

}
Exemple #3
0
QString Unpacker::parse(QString regexp, QString str) const
{
    QRegExp rx;
    rx.setMinimal(true);
    rx.setPattern(regexp);
    rx.indexIn(str);
    if (rx.capturedTexts().size() > 1)
        return rx.capturedTexts().at(1);
    else
        return QString();
}
QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const QString& line)
{
    QString text = line.simplified();

    // comment line: # comment
    static QRegExp comment("\\#.*");
    // title line: keyboard "title"
    static QRegExp title("keyboard\\s+\"(.*)\"");
    // key line: key KeySequence : "output"
    // key line: key KeySequence : command
    static QRegExp key("key\\s+([\\w\\+\\s\\-]+)\\s*:\\s*(\"(.*)\"|\\w+)");

    QList<Token> list;

    if ( text.isEmpty() || comment.exactMatch(text) )
    {
        return list;
    }

    if ( title.exactMatch(text) )
    {
        Token titleToken = { Token::TitleKeyword , QString() };
        Token textToken = { Token::TitleText , title.capturedTexts()[1] };
    
        list << titleToken << textToken;
    }
    else if  ( key.exactMatch(text) )
    {
        Token keyToken = { Token::KeyKeyword , QString() };
        Token sequenceToken = { Token::KeySequence , key.capturedTexts()[1].remove(' ') };

        list << keyToken << sequenceToken;

        if ( key.capturedTexts()[3].isEmpty() )
        {
            // capturedTexts()[2] is a command
            Token commandToken = { Token::Command , key.capturedTexts()[2] };
            list << commandToken;    
        }   
        else
        {
            // capturedTexts()[3] is the output string
           Token outputToken = { Token::OutputText , key.capturedTexts()[3] };
           list << outputToken;
        }     
    }
    else
    {
        kWarning() << "Line in keyboard translator file could not be understood:" << text;
    }

    return list;
}
Exemple #5
0
void LocationShared::setPath( const QString &path ) {
	mPath = path.trimmed();
	mPath.replace( '\\', '/' );

	// Clean off any trailing slashes
	while ( mPath.endsWith( '/' ) && mPath.length() > 1 ) {
		mPath.truncate( mPath.length() - 1 );
	}

	// Work out what kind of path this is. Default if no pattern matches, is local.
	if ( gSftpServerRegExp.indexIn( mPath ) > -1 ) {
		mProtocol = Location::Sftp;
		QStringList parts = gSftpServerRegExp.capturedTexts();
		mRemoteUserName = parts[ 2 ];
		mRemoteHostName = parts[ 3 ];
		mRemotePath = parts[ 4 ];

		if ( mRemotePath.length() == 0 ) {
			mRemotePath = "/";
		}
		mRemotePath.replace( QRegExp( "^/~" ), "~" );
	} else if ( gSshServerRegExp.indexIn( mPath ) > -1 ) {
		mProtocol = Location::Ssh;
		QStringList parts = gSshServerRegExp.capturedTexts();
		mRemoteUserName = parts[ 1 ];
		mRemoteHostName = parts[ 2 ];
		mRemotePath = parts[ 3 ];

		if ( mRemotePath.length() == 0 ) {
			mRemotePath = "/";
		}

		if ( mRemoteUserName.endsWith( '*' ) ) {
			mSudo = true;
			mRemoteUserName.truncate( mRemoteUserName.length() - 1 );
		}
	} else if ( mPath.length() == 0 ) {
		mProtocol = Location::Unsaved;
	} else {
		mProtocol = Location::Local;
	}

	// Work out what to label this path...
	int lastSeparatorIndex = mPath.lastIndexOf(
		mProtocol == Location::Ssh || mProtocol == Location::Sftp ? gSshPathSeparators : gLocalPathSeparators );
	mLabel = mPath.mid( lastSeparatorIndex + 1 );
	if ( mPath == "/" ) {
		mLabel = "Root (/)";
	} else if ( mPath.isEmpty() ) {
		mLabel = QString( "New File %1" ).arg( gOpenFileManager.newFileNumber() );
	}
}
Exemple #6
0
void GmacsPreprocessor::analyze(const QStringList &list, const QRegExp &expression)
{
	int size = list.size();
	for (int i = 0; i < size; i++) {
		QString word = list[i];
		int idx = expression.indexIn(word);
		if (word.isEmpty()) continue;
		while (idx >= 0) {
			int length = expression.matchedLength();
			QString w = word.mid(idx, length).trimmed();
			if (!added_words.contains(w)) {
				QStringList texts = expression.capturedTexts();
				if (texts.size() > 1) {
					qDebug() << texts;
					QString type_name = texts[1].trimmed();
					if (type_name == "struct" &&
						texts.size() > 2 && !texts[2].isEmpty()) {
						type_name = texts[2].trimmed();
					}
					qDebug() << type_name;
					added_words << type_name;
					QStringList property = getTypeObjectLines(list, i);
					//traverseTypeObject(list, i);
				}
			}
			idx = expression.indexIn(word, idx + length);
		}
	}
}
QSObject QSStringClass::match( QSEnv *env )
{
    QString s = env->thisValue().sVal();
    QSObject arg0 = env->arg(0);
    if ( arg0.objectType() == env->regexpClass() ) {
	QRegExp *reg = QSRegExpClass::regExp(&arg0);

	int spos = reg->search(s);
	if (spos == -1) // No match
	    return env->createUndefined();

	if (QSRegExpClass::isGlobal(&arg0)) {
	    QSArray lst(env);
	    int index = 0;
	    while (spos>=0) {
		lst.put(QString::number(index++), env->createString(reg->cap()));
		spos = reg->search(s, spos+1);
	    }
	    if (index == 1)  // only one element, return it
		return lst.get(QString::number(0));
	    return lst;
	} else {
	    return env->createString(reg->cap());
	}
	env->regexpClass()->lastCaptures = reg->capturedTexts();
	QString mstr = reg->cap();
	if ( mstr.isNull() )
	// ### return an array, with the matches
	return env->createString( mstr );
    }
    return env->createUndefined();
}
QString extractCpuInfoLine(int processorNumber, const QString &regExpStr)
{
    if (processorNumber == -1) {
        return QString();
    }

    QFile cpuInfoFile("/proc/cpuinfo");
    if (!cpuInfoFile.open(QIODevice::ReadOnly)) {
        return QString();
    }
    QStringList cpuInfo = QString(cpuInfoFile.readAll()).split('\n', QString::SkipEmptyParts);
    cpuInfoFile.close();

    const QRegExp processorRegExp("processor\\s+:\\s+(\\d+)");
    const QRegExp regExp(regExpStr);

    int line = 0;
    while (line < cpuInfo.size()) {
        if (processorRegExp.exactMatch(cpuInfo.at(line))) {
            int recordProcNum = processorRegExp.capturedTexts()[1].toInt();
            if (recordProcNum == processorNumber) {
                ++line;
                while (line < cpuInfo.size()) {
                    if (regExp.exactMatch(cpuInfo.at(line))) {
                        return regExp.capturedTexts()[1];
                    }
                    ++line;
                }
            }
        }
        ++line;
    }

    return QString();
}
Exemple #9
0
const Card *Card::Parse(const QString &str){
    if(str.startsWith(QChar('@'))){
        // skill card
        static QRegExp pattern("@(\\w+)=(.+)");
        pattern.indexIn(str);
        QStringList texts = pattern.capturedTexts();
        QString card_name = texts.at(1);
        QStringList subcard_ids;
        QString subcard_str = texts.at(2);
        if(subcard_str != ".")
           subcard_ids = subcard_str.split("+");
        SkillCard *card = Sanguosha->cloneSkillCard(card_name);

        if(card == NULL)
            return NULL;

        foreach(QString subcard_id, subcard_ids)
            card->addSubcard(subcard_id.toInt());

        // skill name
        QString skill_name = card_name.remove("Card").toLower();
        card->setSkillName(skill_name);

        return card;        
    }else if(str.startsWith(QChar('$'))){
        QString copy = str;
        copy.remove(QChar('$'));
        QStringList card_strs = copy.split("+");
        DummyCard *dummy = new DummyCard;
        foreach(QString card_str, card_strs){
            dummy->addSubcard(card_str.toInt());
        }
Exemple #10
0
/*!
    \details An user join this channel
    \param l is the string from Irc server
*/
void IrcChannel::userJoin(QString l)
{
    //  :[email protected] JOIN :#testmonkeystudio
    QRegExp r (":([^!]+).*\\sJOIN\\s:([^ ]+)");
    if(r.exactMatch(l))
    {
        QStringList t = r.capturedTexts();
        if(t.at(2).toLower() == name())
        {
            if(userName() != t.at(1))
            {
                QListWidgetItem *newItem = new QListWidgetItem;
                newItem->setText(t.at(1));
                mMemberList->addItem(newItem);

                mTextEdit->appendHtml("<font color=\"#00ff00\">* "  + t.at(1) + " has joined " + name()  + "</font>");
            }
            else 
            {
                // this user is me :)
                mTextEdit->appendHtml("<font color=\"#ff0000\">Now talking in " + name() + "</font>");
            }

        }
    }
}
Exemple #11
0
void MediaBrowser::fileTypeChanged(int selectedIndex)
{
	QString type = m_filterBox->itemData(selectedIndex).toString();

	static QRegExp parse2("(\\*\\.\\w+)\\s*");

	QString list = type;

	m_currentTypeFilterList.clear();
	int pos=0;
	int count=0;
	while(pos>=0)
	{
		pos = parse2.indexIn(list,pos);
		if(pos>=0)
		{
			pos += parse2.matchedLength();
			m_currentTypeFilterList.append(parse2.capturedTexts().at(1));
			count ++;
		}
	}

// 		if(count == 0)
// 		{
// 			qDebug() << "MediaBrowser::fileTypeChanged: parse2 didnt match:"<<list;
// 		}
// 		else
// 		{
// 			qDebug() << "MediaBrowser::fileTypeChanged: parse2 matched:"<<m_currentTypeFilterList;
// 		}

	// re-apply the filters to the file model
	filterChanged(m_searchBox->text());

}
QSObject QSRegExpClass::fetchValue( const QSObject *objPtr,
				    const QSMember &mem ) const
{
    if ( mem.type() != QSMember::Custom )
	return QSWritableClass::fetchValue( objPtr, mem );

    QRegExp *re = regExp( objPtr );
    switch ( mem.index() ) {
    case Valid:
	return createBoolean( re->isValid() );
    case Empty:
	return createBoolean( re->isEmpty() );
    case MLength:
	return createNumber( re->matchedLength() );
    case Source:
	return createString( source(objPtr) );
    case Global:
	return createBoolean( isGlobal(objPtr) );
    case IgnoreCase:
	return createBoolean( isIgnoreCase(objPtr) );
    case CTexts: {
 	QSArray array( env() );
 	QStringList ct = re->capturedTexts();
 	QStringList::ConstIterator it = ct.begin();
 	int i = 0;
 	for ( ; it != ct.end(); ++it, ++i )
 	    array.put( QString::number( i ), createString( *it ) );
	array.put( QString::fromLatin1("length"), createNumber( i ) );
 	return array;
    }
    default:
	return createUndefined();
    }
}
Exemple #13
0
bool blogapp::Post::onLoad(const QString &fullfilename)
{
  if (id.isEmpty())
    return true;

  QRegExp r = QRegExp("^(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)?_(.+)\\.txt$");

  if (!r.exactMatch(id)) {
    // see if its just a basic text file then
    QRegExp txt = QRegExp("^(.+)\\.txt$");
    if (txt.exactMatch(id)) {
      QFileInfo info(fullfilename);
      QDate mod(info.lastModified().date());
      year = mod.year();
      month = mod.month();
      day = mod.day();
      QStringList l = r.capturedTexts();
      title = l[1];
      return true;
    }
    return false;
  }

  QStringList l = r.capturedTexts();
  bool ok;

  assert(l.size() == 5);

  year = l[1].toInt(&ok);
  if (!ok)
    return false;
  month = l[2].toInt(&ok);
  if (!ok)
    return false;
  day = 1;
  if (!l[3].isEmpty()) {
    day = l[3].toInt(&ok);
    if (!ok)
      return false;
  }

  title = l[l.size()-1];
  
  return true;
}
	static QString GetStringFromRX (const QString& pattern, const QString& contents)
	{
		QString result;
		QRegExp rx (pattern);
		if (rx.indexIn (contents) != -1)
			result = rx.capturedTexts ().at (1);
		else
			qWarning () << Q_FUNC_INFO
				<< "nothing captured for pattern"
				<< rx.pattern ();
		return result;
	}
QList<int> SweetDisplayStandby::getVirtualKey(QKeySequence keySequence)
{
    QList<int> keys;
    if ( !keySequence.toString().size() )
    {
        return keys;
    }

    QString sequenceString = keySequence.toString();
    QRegExp rx("\\+");
    QStringList query = sequenceString.split(rx);
    uint modifiers=0;
    int i = 0, vk =-1;
    for (; i <query.length()-1; i++ )
    {
        if( query[i] == "Ctrl" )
        {
            modifiers |= MOD_CONTROL;
        }
        else if( query[i] == "Alt" )
        {
            modifiers |= MOD_ALT;
        }
        else if( query[i] == "Shift" )
        {
            modifiers |= MOD_SHIFT;
        }
        else if( query[i] == "Meta" )
        {
            modifiers |= MOD_WIN;
        }
    }
    QString lastKey = query[i];


    QRegExp frx ( "^F(\\d+)$"); // F group keys
    QRegExp drx ( "^(\\d)$"); //digits
    QRegExp lrx ( "^([A-Z])$"); //capital letters
    frx.indexIn(lastKey);
    drx.indexIn(lastKey);
    lrx.indexIn(lastKey);
    if (frx.capturedTexts()[1].length())
    {
        vk += VK_F1 + frx.capturedTexts()[1].toInt();
    }
    else if (drx.capturedTexts()[1].length())
    {
        QChar c = drx.capturedTexts()[1][0];
        vk = c.toLatin1();
    }
    else if (lrx.capturedTexts()[1].length())
    {
        QChar c = lrx.capturedTexts()[1][0];
        vk = c.toLatin1();
    }
    keys.append(modifiers);
    keys.append(vk);
    return keys;
}
bool QtnPropertyQRectBase::fromStrImpl(const QString& str)
{
    static QRegExp parserRect("^\\s*QRect\\s*\\(([^\\)]+)\\)\\s*$", Qt::CaseInsensitive);
    static QRegExp parserParams("^\\s*(-?\\d+)\\s*,\\s*(-?\\d+)\\s*,\\s*(\\d+)\\s*,\\s*(\\d+)\\s*$", Qt::CaseInsensitive);

    if (!parserRect.exactMatch(str))
        return false;

    QStringList params = parserRect.capturedTexts();
    if (params.size() != 2)
        return false;

    if (!parserParams.exactMatch(params[1]))
        return false;

    params = parserParams.capturedTexts();
    if (params.size() != 5)
        return false;

    bool ok = false;
    int left = params[1].toInt(&ok);
    if (!ok)
        return false;

    int top = params[2].toInt(&ok);
    if (!ok)
        return false;

    int width = params[3].toInt(&ok);
    if (!ok)
        return false;

    int height = params[4].toInt(&ok);
    if (!ok)
        return false;

    setValue(QRect(left, top, width, height));
    return true;
}
bool QtnPropertyQRectFBase::fromStrImpl(const QString& str)
{
    static QRegExp parserRect("^\\s*QRectF\\s*\\(([^\\)]+)\\)\\s*$", Qt::CaseInsensitive);
    static QRegExp parserParams("^\\s*(\\-?\\d+(\\.\\d{0,})?)\\s*,\\s*(\\-?\\d+(\\.\\d{0,})?)\\s*,\\s*(\\d+(\\.\\d{0,})?)\\s*,\\s*(\\d+(\\.\\d{0,})?)\\s*$", Qt::CaseInsensitive);

    if (!parserRect.exactMatch(str))
        return false;

    QStringList params = parserRect.capturedTexts();
    if (params.size() != 2)
        return false;

    if (!parserParams.exactMatch(params[1]))
        return false;

    params = parserParams.capturedTexts();
    if (params.size() != 9)
        return false;

    bool ok = false;
    qreal left = params[1].toDouble(&ok);
    if (!ok)
        return false;

    qreal top = params[3].toDouble(&ok);
    if (!ok)
        return false;

    qreal width = params[5].toDouble(&ok);
    if (!ok)
        return false;

    qreal height = params[7].toDouble(&ok);
    if (!ok)
        return false;

    setValue(QRectF(left, top, width, height));
    return true;
}
Exemple #18
0
/**
 * \brief stepwidth is always relative (it is a double in case axistype == datetime)
 *
 * @param stepwidth to calculate the next step ( must be convertible to int or double)
 */
void evePosCalc::setStepWidth(QString stepwidth) {

    bool ok=false;
    if (axisType == eveDateTimeT){
        // stepwidth is a double, we accept a number or HH:mm:ss.mmm format
        QRegExp regex = QRegExp("^(\\d+):(\\d+):([\\d.]+)$");
        QRegExp duration = QRegExp("^P(\\d+)Y(\\d+)M(\\d+)DT(\\d+)H(\\d+)M([\\d.]+)S$");
        if (stepwidth.contains(regex) && (regex.numCaptures() == 3)){
            QStringList list = regex.capturedTexts();
            int hours = list.at(1).toInt(&ok);
            int minutes = list.at(2).toInt(&ok);
            double seconds = list.at(3).toDouble(&ok) + (double)(60*minutes + 3600*hours);
            stepWidth.setValue(seconds);
        }
        else if (stepwidth.contains(duration) && (duration.numCaptures() == 6)){
            QStringList list = duration.capturedTexts();
            if ((list.at(1).toInt(&ok)!= 0) || (list.at(2).toInt(&ok)!= 0) || (list.at(3).toInt(&ok)!= 0))
                sendError(MINOR, QString("ISO Duration not implemented for Y/M/D (%1)").arg(stepwidth));
            double seconds = list.at(4).toDouble(&ok)*3600 + list.at(5).toDouble(&ok)*60 + list.at(6).toDouble(&ok);
            stepWidth.setValue(seconds);
        }
        else {
            stepWidth.setValue(stepwidth.toDouble(&ok));
        }
        sendError(DEBUG, QString("set stepwidth to %1 (%2)").arg(stepWidth.toDouble(&ok)).arg(stepwidth));
    }
    else if ((stepmode == MULTIPLY) || (axisType == eveDOUBLE)){
        stepWidth.setValue(stepwidth.toDouble(&ok));
    }
    else if (axisType == eveINT){
        stepWidth.setValue(stepwidth.toInt(&ok));
    }
    else if (axisType == eveStringT){
        stepWidth.setValue(stepwidth.toInt(&ok));
    }

    if (!ok) sendError(ERROR, QString("unable to set %1 as stepwidth").arg(stepwidth));
    checkValues();
}
void PairwiseAlignmentHirschbergTask::changeGivenUrlIfDocumentExists(QString & givenUrl, const Project * curProject) {
    if(NULL != curProject->findDocumentByURL(GUrl(givenUrl))) {
        for(size_t i = 1; ; i++) {
            QString tmpUrl = givenUrl;
            QRegExp dotWithExtensionRegExp ("\\.{1,1}[^\\.]*$|^[^\\.]*$");
            dotWithExtensionRegExp.lastIndexIn(tmpUrl);
            tmpUrl.replace(dotWithExtensionRegExp.capturedTexts().last(), "(" + QString::number(i) + ")" + dotWithExtensionRegExp.capturedTexts().last());
            if(NULL == curProject->findDocumentByURL(GUrl(tmpUrl))) {
                givenUrl = tmpUrl;
                break;
            }
        }
    }
}
Exemple #20
0
void TempoText::textChanged()
      {
      if (!_followText)
            return;
      // cache regexp, they are costly to create
      static QHash<QString, QRegExp> regexps;
      static QHash<QString, QRegExp> regexps2;
      QString s = plainText();
      s.replace(",", ".");
      s.replace("<sym>space</sym>"," ");
      for (const TempoPattern& pa : tp) {
            QRegExp re;
            if (!regexps.contains(pa.pattern)) {
                  re = QRegExp(QString("%1\\s*=\\s*(\\d+[.]{0,1}\\d*)\\s*").arg(pa.pattern));
                  regexps[pa.pattern] = re;
                  }
            re = regexps.value(pa.pattern);
            if (re.indexIn(s) != -1) {
                  QStringList sl = re.capturedTexts();
                  if (sl.size() == 2) {
                        qreal nt = qreal(sl[1].toDouble()) * pa.f;
                        if (nt != _tempo) {
                              setTempo(qreal(sl[1].toDouble()) * pa.f);
                              _relative = 1.0;
                              _isRelative = false;
                              updateScore();
                              }
                        break;
                        }
                  }
            else {
                 for (const TempoPattern& pa2 : tp) {
                       QString key = QString("%1_%2").arg(pa.pattern).arg(pa2.pattern);
                       QRegExp re2;
                       if (!regexps2.contains(key)) {
                             re2 = QRegExp(QString("%1\\s*=\\s*%2\\s*").arg(pa.pattern).arg(pa2.pattern));
                             regexps2[key] = re2;
                             }
                       re2 = regexps2.value(key);
                       if (re2.indexIn(s) != -1) {
                             _relative = pa2.f / pa.f;
                             _isRelative = true;
                             updateRelative();
                             updateScore();
                             return;
                             }
                       }
                  }
            }
      }
QString NewExperimentSettingsDialog::CheckExpressionPattern( QString pattern, QString text)
{
    if (text=="") return "";
    int pos=-1;
    QRegExp *exp = new QRegExp(pattern);
    QString matchedword="";
    exp->setPattern(pattern);
    pos=exp->indexIn(text);
    if (pos==0)
    {
        matchedword=exp->capturedTexts().first();
    }
    return matchedword;
}
bool compareVersion(const QVariantMap &imageMap1, const QVariantMap &imageMap2)
{
    // must compare only version not whole string
    // name-8.0.2.img.gz < name-8.0.2.1.img.gz
    // LibreELEC-WeTek_Hub.aarch64-8.0.2.1.img.gz
    QRegExp regExp = QRegExp(".*-([0-9]+.*)\\.img\\.gz");
    regExp.indexIn(imageMap1["name"].toString());
    QStringList versionStr1 = regExp.capturedTexts();
    regExp.indexIn(imageMap2["name"].toString());
    QStringList versionStr2 = regExp.capturedTexts();

    if (versionStr1.count() != 2 || versionStr2.count() != 2)
        return false;   // some error

    int versionCmp = QVersionNumber::compare(
              QVersionNumber::fromString(versionStr1.at(1)),
              QVersionNumber::fromString(versionStr2.at(1)));

    if (versionCmp < 0)
        return false;
    else
        return true;
}
QLyricsList LyricParser::parserLyrics(const QString &lyricsStr)
{
    if (lyricsStr.isEmpty ())
        return QLyricsList();

//    qDebug()<<"LyricParser start parser";

    QRegExp timeExp;
    timeExp.setPatternSyntax(QRegExp::RegExp);
    timeExp.setCaseSensitivity(Qt::CaseSensitive);
    timeExp.setPattern("\\[([0-9]{2}):([0-9]{2})\\.([0-9]{2})\\]");

    QString str = lyricsStr;
    QTextStream stream(&str, QIODevice::ReadOnly);

    QLyricsList result;
    while (!stream.atEnd()) {
        QString line = stream.readLine();

//        qDebug()<<"readline "<<line;

        int ret = timeExp.indexIn(line);
        QList<QTime> ticks;
        int lastindex = 0;
        while (ret >= 0) {
            QStringList tstr = timeExp.capturedTexts();
            QTime time(0, tstr[1].toInt(), tstr[2].toInt(), tstr[3].toInt());
            ticks.append(time);
            lastindex = ret + timeExp.matchedLength();
            ret = timeExp.indexIn(line, lastindex);
        }
        QString lyricstr = line.right(line.size() - lastindex);
        for (const QTime& t : ticks) {
            QLyrics lyrics;
            lyrics.time = t;
            lyrics.lyrics = lyricstr;
//            qDebug()<<"Try to append lyrics line [time] "<<t.toString ()
//                   <<" [text] " <<lyricstr;

            result.append(lyrics);
        }
    }
    qStableSort(result.begin(),
              result.end(),
              [] (const QLyrics& a, const QLyrics& b) -> bool {
        return a.time < b.time;
    });

    return result;
}
Exemple #24
0
/*!
    \details An user as changed a nick
    \param s is the string from Irc server
*/
void IrcChannel::userNickChange(QString s)
{
    // :[email protected] NICK :dddtre
    QRegExp r (":([^!]+).*\\sNICK\\s:(.*)");
    if(r.exactMatch(s)) 
    {
        QStringList l = r.capturedTexts();
        QListWidgetItem *it = findUser(l.at(1));
        if(it)
        {
            it->setText( hasPrivilege(it->text()) + l.at(2));
            mTextEdit->appendHtml("<font color=\"#ff0000\">User " + l.at(1) + " is now know as " + l.at(2) + "</font>");
        }
    }
}
Exemple #25
0
/*!
    \details An user quit Irc server
    \param l is the string from Irc server
*/
void IrcChannel::userQuit(QString l)
{
    //:ThomasGHenry!n=tghenry@nat/ibm/x-e360141219a099ca QUIT :"Leaving."
    QRegExp r (":([^!]+).*\\sQUIT\\s:(.*)");
    if(r.exactMatch(l))
    {
        QStringList t = r.capturedTexts();
        QListWidgetItem *it = findUser(t.at(1));
        if( it )
        {
            mMemberList->removeItemWidget( it );
            delete it;
            mTextEdit->appendHtml("<font color=\"#0000ff\">* " + t.at(1) + " has quit " + name() + " " + t.at(2) + "</font>");
        }
    }
}
void QgsDelimitedTextFile::setFieldNames( const QStringList &names )
{
  mFieldNames.clear();
  foreach ( QString name, names )
  {
    bool nameOk = true;
    int fieldNo = mFieldNames.size() + 1;
    name = name.trimmed();
    if ( name.length() > mMaxNameLength ) name = name.mid( 0, mMaxNameLength );

    // If the name is invalid then reset it to default name
    if ( InvalidFieldRegexp.exactMatch( name ) )
    {
      name = DefaultFieldName.arg( fieldNo );
    }
    // If the name looks like a default field name (field_##), then it is
    // valid if the number matches its column number..
    else if ( DefaultFieldRegexp.indexIn( name ) == 0 )
    {
      int col = DefaultFieldRegexp.capturedTexts()[1].toInt();
      nameOk = col == fieldNo;
    }
    // Otherwise it is valid if isn't the name of an existing field...
    else
    {
      nameOk = ! mFieldNames.contains( name, Qt::CaseInsensitive );
    }
    // If it is not a valid name then try appending a number to generate
    // a valid name.
    if ( ! nameOk )
    {
      int suffix = 0;
      QString basename = name + "_%1";
      while ( true )
      {
        suffix++;
        name = basename.arg( suffix );
        // Not ok if it is already in the name list
        if ( mFieldNames.contains( name, Qt::CaseInsensitive ) ) continue;
        // Not ok if it is already in proposed names
        if ( names.contains( name, Qt::CaseInsensitive ) ) continue;
        break;
      }
    }
    mFieldNames.append( name );
  }
Exemple #27
0
/**
 *
 * @param position start or end position relative or absolute
 * @param posVariant the variant startpos or endpos
 */
void evePosCalc::setPos(QString position, eveVariant* posVariant) {

    if ((axisType == eveDateTimeT) && absolute){
        // absolute: we accept only "yyyy-MM-dd HH:mm:ss(.zzz)" or "HH:mm:ss(.zzz)" format
        if (!position.contains(QRegExp("^\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}:\\d{1,2}:\\d{1,2}([.]\\d{1,3})?$")) &&
                !position.contains(QRegExp("^\\d{1,2}:\\d{1,2}:\\d{1,2}([.]\\d{1,3})?$"))){
            sendError(ERROR, QString("invalid absolute datetime format %1, using current time").arg(position));
            posVariant->setValue(QDateTime::currentDateTime());
            return;
        }
    }
    else if ((axisType == eveDateTimeT) && !absolute){
        // relative: we accept an ISO duration format or obsolete HH:mm:ss
        QRegExp duration = QRegExp("^P(\\d+)Y(\\d+)M(\\d+)DT(\\d+)H(\\d+)M([\\d.]+)S$");
        if (position.contains(duration) && (duration.numCaptures() == 6)){
            bool ok;
            QStringList list = duration.capturedTexts();
            if ((list.at(1).toInt(&ok)!= 0) || (list.at(2).toInt(&ok)!= 0) || (list.at(3).toInt(&ok)!= 0))
                sendError(MINOR, QString("ISO Duration not implemented for Y/M/D (%1)").arg(position));
            double seconds = list.at(4).toDouble(&ok)*3600 + list.at(5).toDouble(&ok)*60 + list.at(6).toDouble(&ok);
            posVariant->setValue(seconds);
            return ;
        }
        // obsolete relative format accepts only a number for seconds or HH:mm:ss format
        else if (position.contains(QRegExp("^\\d{1,2}:\\d{1,2}:\\d{1,2}([.]\\d{1,3})?$"))){
            // obsolete relative format accepts only a number for seconds or HH:mm:ss format
            QString format;
            if (position.contains("."))
                format = "h:m:s.z";
            else
                format = "h:m:s";
            posVariant->setValue(QDateTime::fromString(position,format));
            return;
        }
        else {
            sendError(ERROR, QString("invalid relative datetime format %1, using 0").arg(position));
            posVariant->setValue(QDateTime());
            return;
        }
    }
    if (!posVariant->setValue(position))
        sendError(ERROR, QString("unable to set %1 as start/end position").arg(position));
    checkValues();
    return;
}
bool PerforceParser::parseNormalDiffHeader()
{
	bool result = false;

	QStringList::ConstIterator itEnd = m_diffLines.end();

	QRegExp sourceFileRE     ( "([^\\#]+)#(\\d+)" );
	QRegExp destinationFileRE( "([^\\#]+)#(|\\d+)" );

	while ( m_diffIterator != itEnd )
	{
		qCDebug(LIBKOMPAREDIFF2) << "Line = " << *m_diffIterator;
		qCDebug(LIBKOMPAREDIFF2) << "String length  = " << (*m_diffIterator).length();
		if ( m_normalDiffHeader.exactMatch( *(m_diffIterator)++ ) )
		{
			qCDebug(LIBKOMPAREDIFF2) << "Matched length Header1 = " << m_normalDiffHeader.matchedLength();
			qCDebug(LIBKOMPAREDIFF2) << "Matched string Header1 = " << m_normalDiffHeader.cap( 0 );
			qCDebug(LIBKOMPAREDIFF2) << "First  capture Header1 = \"" << m_normalDiffHeader.cap( 1 ) << "\"";
			qCDebug(LIBKOMPAREDIFF2) << "Second capture Header1 = \"" << m_normalDiffHeader.cap( 2 ) << "\"";

			m_currentModel = new DiffModel();
			sourceFileRE.exactMatch( m_normalDiffHeader.cap( 1 ) );
			destinationFileRE.exactMatch( m_normalDiffHeader.cap( 2 ) );
			qCDebug(LIBKOMPAREDIFF2) << "Matched length   = " << sourceFileRE.matchedLength();
			qCDebug(LIBKOMPAREDIFF2) << "Matched length   = " << destinationFileRE.matchedLength();
			qCDebug(LIBKOMPAREDIFF2) << "Captured texts   = " << sourceFileRE.capturedTexts();
			qCDebug(LIBKOMPAREDIFF2) << "Captured texts   = " << destinationFileRE.capturedTexts();
			qCDebug(LIBKOMPAREDIFF2) << "Source File      : " << sourceFileRE.cap( 1 );
			qCDebug(LIBKOMPAREDIFF2) << "Destination File : " << destinationFileRE.cap( 1 );
			m_currentModel->setSourceFile     ( sourceFileRE.cap( 1 ) );
			m_currentModel->setDestinationFile( destinationFileRE.cap( 1 ) );

			result = true;

			break;
		}
		else
		{
			qCDebug(LIBKOMPAREDIFF2) << "Matched length = " << m_normalDiffHeader.matchedLength();
			qCDebug(LIBKOMPAREDIFF2) << "Captured texts = " << m_normalDiffHeader.capturedTexts();
		}
	}

	return result;
}
static QString stripLinksFromText(const QString& _text)
{
	static QRegExp href("\\<a href.+\\>(.+)\\<\\/a\\>");
	href.setMinimal(true);

	QString text = TextUtil::linkify(_text);
	if (text != _text) {
		int index = text.indexOf(href);
		Q_ASSERT(index >= 0);
		while (index >= 0) {
			int length = href.matchedLength();
			QString unescapedUrl = TextUtil::unescape(href.capturedTexts()[1]);
			text.replace(index, length, QString(unescapedUrl.length(), ' '));
			index = text.indexOf(href, index + unescapedUrl.length());
		}
	}
	return text;
}
QSObject QSRegExpClass::test( QSEnv *env )
{
    QSObject obj = env->thisValue();
    QRegExp *re = regExp( &obj );
    QString s = env->arg( 0 ).toString();
    uint length = s.length();
    int i = obj.get( QString::fromLatin1("lastIndex") ).toInt32();
    QSObject tmp = obj.get( QString::fromLatin1("global") );
    if ( !tmp.toBoolean() )
	i = 0;
    if ( i < 0 || i >(int) length ) {
	obj.put( QString::fromLatin1("lastIndex"), 0 );
	return env->createBoolean( FALSE );
    }
    i = re->search( s, i );
    obj.env()->regexpClass()->lastCaptures = re->capturedTexts();
    return env->createBoolean( i >= 0 );
}