20#include <QTextBoundaryFinder>
21#include <QRegularExpression>
26 if (
string.isEmpty() )
29 switch ( capitalization )
36 return string.toUpper();
40 return string.toLower();
44 QString temp = string;
46 QTextBoundaryFinder wordSplitter( QTextBoundaryFinder::Word,
string.constData(),
string.length(),
nullptr, 0 );
47 QTextBoundaryFinder letterSplitter( QTextBoundaryFinder::Grapheme,
string.constData(),
string.length(),
nullptr, 0 );
49 wordSplitter.setPosition( 0 );
51 while ( ( first && wordSplitter.boundaryReasons() & QTextBoundaryFinder::StartOfItem )
52 || wordSplitter.toNextBoundary() >= 0 )
55 letterSplitter.setPosition( wordSplitter.position() );
56 letterSplitter.toNextBoundary();
57 QString substr =
string.mid( wordSplitter.position(), letterSplitter.position() - wordSplitter.position() );
58 temp.replace( wordSplitter.position(), substr.length(), substr.toUpper() );
67 static QStringList smallWords;
68 static QStringList newPhraseSeparators;
69 static QRegularExpression splitWords;
70 if ( smallWords.empty() )
72 smallWords = QObject::tr(
"a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|s|the|to|vs.|vs|via" ).split(
'|' );
73 newPhraseSeparators = QObject::tr(
".|:" ).split(
'|' );
74 splitWords = QRegularExpression( QStringLiteral(
"\\b" ), QRegularExpression::UseUnicodePropertiesOption );
77 const bool allSameCase =
string.toLower() ==
string ||
string.toUpper() == string;
78#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
79 const QStringList parts = ( allSameCase ?
string.toLower() : string ).split( splitWords, QString::SkipEmptyParts );
81 const QStringList parts = ( allSameCase ?
string.toLower() : string ).split( splitWords, Qt::SkipEmptyParts );
84 bool firstWord =
true;
86 int lastWord = parts.count() - 1;
87 for (
const QString &word : std::as_const( parts ) )
89 if ( newPhraseSeparators.contains( word.trimmed() ) )
94 else if ( firstWord || ( i == lastWord ) || !smallWords.contains( word ) )
96 result += word.at( 0 ).toUpper() + word.mid( 1 );
110 result.remove(
' ' );
121 for (
int i = 0; i <
string.size(); ++i )
123 QChar ch =
string.at( i );
124 if ( ch.unicode() > 160 )
125 encoded += QStringLiteral(
"&#%1;" ).arg(
static_cast< int >( ch.unicode() ) );
126 else if ( ch.unicode() == 38 )
127 encoded += QLatin1String(
"&" );
128 else if ( ch.unicode() == 60 )
129 encoded += QLatin1String(
"<" );
130 else if ( ch.unicode() == 62 )
131 encoded += QLatin1String(
">" );
140 int length1 = string1.length();
141 int length2 = string2.length();
144 if ( string1.isEmpty() )
148 else if ( string2.isEmpty() )
154 QString s1( caseSensitive ? string1 : string1.toLower() );
155 QString s2( caseSensitive ? string2 : string2.toLower() );
157 const QChar *s1Char = s1.constData();
158 const QChar *s2Char = s2.constData();
161 int commonPrefixLen = 0;
162 while ( length1 > 0 && length2 > 0 && *s1Char == *s2Char )
172 while ( length1 > 0 && length2 > 0 && s1.at( commonPrefixLen + length1 - 1 ) == s2.at( commonPrefixLen + length2 - 1 ) )
183 else if ( length2 == 0 )
189 if ( length1 > length2 )
192 std::swap( length1, length2 );
196 std::vector< int > col( length2 + 1, 0 );
197 std::vector< int > prevCol;
198 prevCol.reserve( length2 + 1 );
199 for (
int i = 0; i < length2 + 1; ++i )
201 prevCol.emplace_back( i );
203 const QChar *s2start = s2Char;
204 for (
int i = 0; i < length1; ++i )
208 for (
int j = 0; j < length2; ++j )
210 col[j + 1] = std::min( std::min( 1 + col[j], 1 + prevCol[1 + j] ), prevCol[j] + ( ( *s1Char == *s2Char ) ? 0 : 1 ) );
216 return prevCol[length2];
221 if ( string1.isEmpty() || string2.isEmpty() )
228 QString s1( caseSensitive ? string1 : string1.toLower() );
229 QString s2( caseSensitive ? string2 : string2.toLower() );
237 int *currentScores =
new int [ s2.length()];
238 int *previousScores =
new int [ s2.length()];
239 int maxCommonLength = 0;
240 int lastMaxBeginIndex = 0;
242 const QChar *s1Char = s1.constData();
243 const QChar *s2Char = s2.constData();
244 const QChar *s2Start = s2Char;
246 for (
int i = 0; i < s1.length(); ++i )
248 for (
int j = 0; j < s2.length(); ++j )
250 if ( *s1Char != *s2Char )
252 currentScores[j] = 0;
256 if ( i == 0 || j == 0 )
258 currentScores[j] = 1;
262 currentScores[j] = 1 + previousScores[j - 1];
265 if ( maxCommonLength < currentScores[j] )
267 maxCommonLength = currentScores[j];
268 lastMaxBeginIndex = i;
273 std::swap( currentScores, previousScores );
277 delete [] currentScores;
278 delete [] previousScores;
279 return string1.mid( lastMaxBeginIndex - maxCommonLength + 1, maxCommonLength );
284 if ( string1.isEmpty() && string2.isEmpty() )
290 if ( string1.length() != string2.length() )
297 QString s1( caseSensitive ? string1 : string1.toLower() );
298 QString s2( caseSensitive ? string2 : string2.toLower() );
307 const QChar *s1Char = s1.constData();
308 const QChar *s2Char = s2.constData();
310 for (
int i = 0; i < string1.length(); ++i )
312 if ( *s1Char != *s2Char )
323 if (
string.isEmpty() )
326 QString tmp =
string.toUpper();
329 QChar *char1 = tmp.data();
330 QChar *char2 = tmp.data();
332 for (
int i = 0; i < tmp.length(); ++i, ++char2 )
334 if ( ( *char2 ).unicode() >= 0x41 && ( *char2 ).unicode() <= 0x5A && ( i == 0 || ( ( *char2 ).unicode() != 0x41 && ( *char2 ).unicode() != 0x45
335 && ( *char2 ).unicode() != 0x48 && ( *char2 ).unicode() != 0x49
336 && ( *char2 ).unicode() != 0x4F && ( *char2 ).unicode() != 0x55
337 && ( *char2 ).unicode() != 0x57 && ( *char2 ).unicode() != 0x59 ) ) )
344 tmp.truncate( outLen );
346 QChar *tmpChar = tmp.data();
348 for (
int i = 1; i < tmp.length(); ++i, ++tmpChar )
350 switch ( ( *tmpChar ).unicode() )
356 tmp.replace( i, 1, QChar( 0x31 ) );
367 tmp.replace( i, 1, QChar( 0x32 ) );
372 tmp.replace( i, 1, QChar( 0x33 ) );
376 tmp.replace( i, 1, QChar( 0x34 ) );
381 tmp.replace( i, 1, QChar( 0x35 ) );
385 tmp.replace( i, 1, QChar( 0x36 ) );
395 for (
int i = 1; i < tmp.length(); ++i, ++char2 )
397 if ( *char2 != *char1 )
406 tmp.truncate( outLen );
407 if ( tmp.length() < 4 )
419 QString candidateNormalized = candidate.simplified().normalized( QString:: NormalizationForm_C ).toLower();
420 QString searchNormalized = search.simplified().normalized( QString:: NormalizationForm_C ).toLower();
422 int candidateLength = candidateNormalized.length();
423 int searchLength = searchNormalized.length();
427 if ( candidateLength == 0 || searchLength == 0 )
430 int candidateIdx = 0;
435 bool isPreviousIndexMatching =
false;
436 bool isWordOpen =
true;
439 while ( candidateIdx < candidateLength )
441 QChar candidateChar = candidateNormalized[ candidateIdx++ ];
442 bool isCandidateCharWordEnd = candidateChar ==
' ' || candidateChar.isPunct();
445 if ( candidateIdx == 1 )
448 else if ( isCandidateCharWordEnd )
455 if ( searchIdx >= searchLength )
458 QChar searchChar = searchNormalized[ searchIdx ];
459 bool isSearchCharWordEnd = searchChar ==
' ' || searchChar.isPunct();
462 if ( candidateChar == searchChar || ( isCandidateCharWordEnd && isSearchCharWordEnd ) )
467 if ( isSearchCharWordEnd )
471 else if ( isPreviousIndexMatching )
479 else if ( isPreviousIndexMatching )
489 isPreviousIndexMatching =
true;
494 isPreviousIndexMatching =
false;
499 if ( searchIdx >= searchLength )
501 bool isEndOfWord = ( candidateIdx >= candidateLength )
503 : candidateNormalized[candidateIdx] ==
' ' || candidateNormalized[candidateIdx].isPunct();
514 if ( searchIdx < searchLength )
517 return static_cast<float>( std::max( score, 0 ) ) / std::max( maxScore, 1 );
523 QString converted = string;
527 const thread_local QRegularExpression urlRegEx( QStringLiteral(
"(\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~\\s]|/))))" ) );
528 const thread_local QRegularExpression protoRegEx( QStringLiteral(
"^(?:f|ht)tps?://|file://" ) );
529 const thread_local QRegularExpression emailRegEx( QStringLiteral(
"([\\w._%+-]+@[\\w.-]+\\.[A-Za-z]+)" ) );
533 QRegularExpressionMatch match = urlRegEx.match( converted );
534 while ( match.hasMatch() )
537 QString url = match.captured( 1 );
538 QString protoUrl = url;
539 if ( !protoRegEx.match( protoUrl ).hasMatch() )
541 protoUrl.prepend(
"http://" );
543 QString anchor = QStringLiteral(
"<a href=\"%1\">%2</a>" ).arg( protoUrl.toHtmlEscaped(), url.toHtmlEscaped() );
544 converted.replace( match.capturedStart( 1 ), url.length(), anchor );
545 offset = match.capturedStart( 1 ) + anchor.length();
546 match = urlRegEx.match( converted, offset );
550 match = emailRegEx.match( converted );
551 while ( match.hasMatch() )
554 QString email = match.captured( 1 );
555 QString anchor = QStringLiteral(
"<a href=\"mailto:%1\">%1</a>" ).arg( email.toHtmlEscaped() );
556 converted.replace( match.capturedStart( 1 ), email.length(), anchor );
557 offset = match.capturedStart( 1 ) + anchor.length();
558 match = emailRegEx.match( converted, offset );
569 const thread_local QRegularExpression rxUrl( QStringLiteral(
"^(http|https|ftp|file)://\\S+$" ) );
570 return rxUrl.match(
string ).hasMatch();
576 QString converted = html;
577 converted.replace( QLatin1String(
"<br>" ), QLatin1String(
"\n" ) );
578 converted.replace( QLatin1String(
"<b>" ), QLatin1String(
"**" ) );
579 converted.replace( QLatin1String(
"</b>" ), QLatin1String(
"**" ) );
580 converted.replace( QLatin1String(
"<pre>" ), QLatin1String(
"\n```\n" ) );
581 converted.replace( QLatin1String(
"</pre>" ), QLatin1String(
"```\n" ) );
583 const thread_local QRegularExpression hrefRegEx( QStringLiteral(
"<a\\s+href\\s*=\\s*([^<>]*)\\s*>([^<>]*)</a>" ) );
586 QRegularExpressionMatch match = hrefRegEx.match( converted );
587 while ( match.hasMatch() )
589 QString url = match.captured( 1 ).replace( QLatin1String(
"\"" ), QString() );
590 url.replace(
'\'', QString() );
591 QString name = match.captured( 2 );
592 QString anchor = QStringLiteral(
"[%1](%2)" ).arg( name, url );
593 converted.replace( match.capturedStart(), match.capturedLength(), anchor );
594 offset = match.capturedStart() + anchor.length();
595 match = hrefRegEx.match( converted, offset );
601QString
QgsStringUtils::wordWrap(
const QString &
string,
const int length,
const bool useMaxLineLength,
const QString &customDelimiter )
603 if (
string.isEmpty() || length == 0 )
607 QRegularExpression rx;
608 int delimiterLength = 0;
610 if ( !customDelimiter.isEmpty() )
612 rx.setPattern( QRegularExpression::escape( customDelimiter ) );
613 delimiterLength = customDelimiter.length();
618 rx.setPattern( QStringLiteral(
"[\\x{200B}\\s]" ) );
622 const QStringList lines =
string.split(
'\n' );
623 int strLength, strCurrent, strHit, lastHit;
625 for (
int i = 0; i < lines.size(); i++ )
627 const QString line = lines.at( i );
628 strLength = line.length();
629 if ( strLength <= length )
632 newstr.append( line );
633 if ( i < lines.size() - 1 )
634 newstr.append(
'\n' );
641 while ( strCurrent < strLength )
645 if ( useMaxLineLength )
648 strHit = ( strCurrent + length >= strLength ) ? -1 : line.lastIndexOf( rx, strCurrent + length );
649 if ( strHit == lastHit || strHit == -1 )
652 strHit = ( strCurrent + std::abs( length ) >= strLength ) ? -1 : line.indexOf( rx, strCurrent + std::abs( length ) );
658 strHit = ( strCurrent + std::abs( length ) >= strLength ) ? -1 : line.indexOf( rx, strCurrent + std::abs( length ) );
662#if QT_VERSION < QT_VERSION_CHECK(5, 15, 2)
663 newstr.append( line.midRef( strCurrent, strHit - strCurrent ) );
665 newstr.append( QStringView {line} .mid( strCurrent, strHit - strCurrent ) );
667 newstr.append(
'\n' );
668 strCurrent = strHit + delimiterLength;
672#if QT_VERSION < QT_VERSION_CHECK(5, 15, 2)
673 newstr.append( line.midRef( strCurrent ) );
675 newstr.append( QStringView {line} .mid( strCurrent ) );
677 strCurrent = strLength;
680 if ( i < lines.size() - 1 )
681 newstr.append(
'\n' );
689 string =
string.replace(
',', QChar( 65040 ) ).replace( QChar( 8229 ), QChar( 65072 ) );
690 string =
string.replace( QChar( 12289 ), QChar( 65041 ) ).replace( QChar( 12290 ), QChar( 65042 ) );
691 string =
string.replace(
':', QChar( 65043 ) ).replace(
';', QChar( 65044 ) );
692 string =
string.replace(
'!', QChar( 65045 ) ).replace(
'?', QChar( 65046 ) );
693 string =
string.replace( QChar( 12310 ), QChar( 65047 ) ).replace( QChar( 12311 ), QChar( 65048 ) );
694 string =
string.replace( QChar( 8230 ), QChar( 65049 ) );
695 string =
string.replace( QChar( 8212 ), QChar( 65073 ) ).replace( QChar( 8211 ), QChar( 65074 ) );
696 string =
string.replace(
'_', QChar( 65075 ) ).replace( QChar( 65103 ), QChar( 65076 ) );
697 string =
string.replace(
'(', QChar( 65077 ) ).replace(
')', QChar( 65078 ) );
698 string =
string.replace(
'{', QChar( 65079 ) ).replace(
'}', QChar( 65080 ) );
699 string =
string.replace(
'<', QChar( 65087 ) ).replace(
'>', QChar( 65088 ) );
700 string =
string.replace(
'[', QChar( 65095 ) ).replace(
']', QChar( 65096 ) );
701 string =
string.replace( QChar( 12308 ), QChar( 65081 ) ).replace( QChar( 12309 ), QChar( 65082 ) );
702 string =
string.replace( QChar( 12304 ), QChar( 65083 ) ).replace( QChar( 12305 ), QChar( 65084 ) );
703 string =
string.replace( QChar( 12298 ), QChar( 65085 ) ).replace( QChar( 12299 ), QChar( 65086 ) );
704 string =
string.replace( QChar( 12300 ), QChar( 65089 ) ).replace( QChar( 12301 ), QChar( 65090 ) );
705 string =
string.replace( QChar( 12302 ), QChar( 65091 ) ).replace( QChar( 12303 ), QChar( 65092 ) );
712 const QLatin1Char backslash(
'\\' );
713 const int count =
string.count();
716 escaped.reserve( count * 2 );
717 for (
int i = 0; i < count; i++ )
719 switch (
string.at( i ).toLatin1() )
735 escaped.append( backslash );
737 escaped.append(
string.at( i ) );
744 const int charactersToTruncate =
string.length() - maxLength;
745 if ( charactersToTruncate <= 0 )
749 const int truncateFrom =
string.length() / 2 - ( charactersToTruncate + 1 ) / 2;
751#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
752 return string.leftRef( truncateFrom ) + QString( QChar( 0x2026 ) ) +
string.midRef( truncateFrom + charactersToTruncate + 1 );
754 return QStringView(
string ).first( truncateFrom ) + QString( QChar( 0x2026 ) ) + QStringView(
string ).sliced( truncateFrom + charactersToTruncate + 1 );
760 , mReplacement( replacement )
761 , mCaseSensitive( caseSensitive )
762 , mWholeWordOnly( wholeWordOnly )
764 if ( mWholeWordOnly )
766 mRx.setPattern( QStringLiteral(
"\\b%1\\b" ).arg( mMatch ) );
767 mRx.setPatternOptions( mCaseSensitive ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption );
773 QString result = input;
774 if ( !mWholeWordOnly )
776 return result.replace( mMatch, mReplacement, mCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive );
780 return result.replace( mRx, mReplacement );
787 map.insert( QStringLiteral(
"match" ), mMatch );
788 map.insert( QStringLiteral(
"replace" ), mReplacement );
789 map.insert( QStringLiteral(
"caseSensitive" ), mCaseSensitive ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
790 map.insert( QStringLiteral(
"wholeWord" ), mWholeWordOnly ? QStringLiteral(
"1" ) : QStringLiteral(
"0" ) );
797 properties.value( QStringLiteral(
"replace" ) ),
798 properties.value( QStringLiteral(
"caseSensitive" ), QStringLiteral(
"0" ) ) == QLatin1String(
"1" ),
799 properties.value( QStringLiteral(
"wholeWord" ), QStringLiteral(
"0" ) ) == QLatin1String(
"1" ) );
804 QString result = input;
807 result = r.process( result );
817 QDomElement propEl = doc.createElement( QStringLiteral(
"replacement" ) );
818 QgsStringMap::const_iterator it = props.constBegin();
819 for ( ; it != props.constEnd(); ++it )
821 propEl.setAttribute( it.key(), it.value() );
823 elem.appendChild( propEl );
829 mReplacements.clear();
830 QDomNodeList nodelist = elem.elementsByTagName( QStringLiteral(
"replacement" ) );
831 for (
int i = 0; i < nodelist.count(); i++ )
833 QDomElement replacementElem = nodelist.at( i ).toElement();
834 QDomNamedNodeMap nodeMap = replacementElem.attributes();
837 for (
int j = 0; j < nodeMap.count(); ++j )
839 props.insert( nodeMap.item( j ).nodeName(), nodeMap.item( j ).nodeValue() );
Capitalization
String capitalization options.
@ AllSmallCaps
Force all characters to small caps (since QGIS 3.24)
@ MixedCase
Mixed case, ie no change.
@ UpperCamelCase
Convert the string to upper camel case. Note that this method does not unaccent characters.
@ AllLowercase
Convert all characters to lowercase.
@ TitleCase
Simple title case conversion - does not fully grammatically parse the text and uses simple rules only...
@ SmallCaps
Mixed case small caps (since QGIS 3.24)
@ ForceFirstLetterToCapital
Convert just the first letter of each word to uppercase, leave the rest untouched.
@ AllUppercase
Convert all characters to uppercase.
void readXml(const QDomElement &elem)
Reads the collection state from an XML element.
QString process(const QString &input) const
Processes a given input string, applying any valid replacements which should be made using QgsStringR...
void writeXml(QDomElement &elem, QDomDocument &doc) const
Writes the collection state to an XML element.
A representation of a single string replacement.
static QgsStringReplacement fromProperties(const QgsStringMap &properties)
Creates a new QgsStringReplacement from an encoded properties map.
QString process(const QString &input) const
Processes a given input string, applying any valid replacements which should be made.
QgsStringReplacement(const QString &match, const QString &replacement, bool caseSensitive=false, bool wholeWordOnly=false)
Constructor for QgsStringReplacement.
QgsStringMap properties() const
Returns a map of the replacement properties.
static int hammingDistance(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the Hamming distance between two strings.
static QString soundex(const QString &string)
Returns the Soundex representation of a string.
static int levenshteinDistance(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the Levenshtein edit distance between two strings.
static QString htmlToMarkdown(const QString &html)
Convert simple HTML to markdown.
static QString longestCommonSubstring(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the longest common substring between two strings.
static QString capitalize(const QString &string, Qgis::Capitalization capitalization)
Converts a string by applying capitalization rules to the string.
static QString substituteVerticalCharacters(QString string)
Returns a string with characters having vertical representation form substituted.
static QString insertLinks(const QString &string, bool *foundLinks=nullptr)
Returns a string with any URL (e.g., http(s)/ftp) and mailto: text converted to valid HTML <a ....
static double fuzzyScore(const QString &candidate, const QString &search)
Tests a candidate string to see how likely it is a match for a specified search string.
static QString qRegExpEscape(const QString &string)
Returns an escaped string matching the behavior of QRegExp::escape.
static QString ampersandEncode(const QString &string)
Makes a raw string safe for inclusion as a HTML/XML string literal.
static QString wordWrap(const QString &string, int length, bool useMaxLineLength=true, const QString &customDelimiter=QString())
Automatically wraps a string by inserting new line characters at appropriate locations in the string.
static bool isUrl(const QString &string)
Returns whether the string is a URL (http,https,ftp,file)
static QString truncateMiddleOfString(const QString &string, int maxLength)
Truncates a string to the specified maximum character length.
QMap< QString, QString > QgsStringMap
#define FUZZY_SCORE_CONSECUTIVE_MATCH
#define FUZZY_SCORE_WORD_MATCH
#define FUZZY_SCORE_NEW_MATCH