23#include <QRegularExpression>
26#include <QTextBoundaryFinder>
30using namespace Qt::StringLiterals;
36 constexpr char16_t MAX_SIMPLE_CHAR = 127;
37 if ( std::none_of( input.cbegin(), input.cend(), []( QChar
c ) { return c.unicode() > MAX_SIMPLE_CHAR; } ) )
48 const QString in = input.normalized( QString::NormalizationForm_C );
50 out.reserve( in.size() );
53 const qsizetype n = in.size();
57 const QChar
c = in.at( i );
59 if (
c.unicode() <= MAX_SIMPLE_CHAR )
69 char32_t ucs4 =
c.unicode();
72 if (
c.isHighSurrogate() && i + 1 < n )
74 const QChar c2 = in.at( i + 1 );
75 if ( c2.isLowSurrogate() )
77 ucs4 = QChar::surrogateToUcs4(
c, c2 );
82 auto it = UNACCENT_MAP.constFind( ucs4 );
83 if ( it != UNACCENT_MAP.constEnd() )
85 out.append( it.value() );
92 out.append( in.at( i + 1 ) );
105 const QString uuid = QUuid::createUuid().toString( QUuid::StringFormat::WithoutBraces );
106 QString
id = base.isEmpty() ? uuid : base +
'_' + uuid;
110 const thread_local QRegularExpression idRx( uR
"([\W])"_s );
111 id.replace( idRx, u
"_"_s );
117 if (
string.isEmpty() )
120 switch ( capitalization )
127 return string.toUpper();
131 return string.toLower();
135 QString temp = string;
137 QTextBoundaryFinder wordSplitter( QTextBoundaryFinder::Word,
string.constData(),
string.length(),
nullptr, 0 );
138 QTextBoundaryFinder letterSplitter( QTextBoundaryFinder::Grapheme,
string.constData(),
string.length(),
nullptr, 0 );
140 wordSplitter.setPosition( 0 );
142 while ( ( first && wordSplitter.boundaryReasons() & QTextBoundaryFinder::StartOfItem ) || wordSplitter.toNextBoundary() >= 0 )
145 letterSplitter.setPosition( wordSplitter.position() );
146 ( void ) letterSplitter.toNextBoundary();
147 QString substr =
string.mid( wordSplitter.position(), letterSplitter.position() - wordSplitter.position() );
148 temp.replace( wordSplitter.position(), substr.length(), substr.toUpper() );
157 const thread_local QStringList 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(
'|' );
158 const thread_local QStringList newPhraseSeparators = QObject::tr(
".|:" ).split(
'|' );
159 const thread_local QRegularExpression splitWords = QRegularExpression( u
"\\b"_s, QRegularExpression::UseUnicodePropertiesOption );
161 const bool allSameCase =
string.toLower() ==
string ||
string.toUpper() == string;
162 const QStringList parts = ( allSameCase ?
string.toLower() :
string ).split( splitWords, Qt::SkipEmptyParts );
164 bool firstWord =
true;
166 int lastWord = parts.count() - 1;
167 for (
const QString &word : std::as_const( parts ) )
169 if ( newPhraseSeparators.contains( word.trimmed() ) )
174 else if ( firstWord || ( i == lastWord ) || !smallWords.contains( word ) )
176 result += word.at( 0 ).toUpper() + word.mid( 1 );
190 result.remove(
' ' );
201 for (
int i = 0; i <
string.size(); ++i )
203 QChar ch =
string.at( i );
204 if ( ch.unicode() > 160 )
205 encoded += u
"&#%1;"_s.arg(
static_cast< int >( ch.unicode() ) );
206 else if ( ch.unicode() == 38 )
207 encoded +=
"&"_L1;
208 else if ( ch.unicode() == 60 )
209 encoded +=
"<"_L1;
210 else if ( ch.unicode() == 62 )
211 encoded +=
">"_L1;
220 int length1 = string1.length();
221 int length2 = string2.length();
224 if ( string1.isEmpty() )
228 else if ( string2.isEmpty() )
234 QString s1( caseSensitive ? string1 : string1.toLower() );
235 QString s2( caseSensitive ? string2 : string2.toLower() );
237 const QChar *s1Char = s1.constData();
238 const QChar *s2Char = s2.constData();
241 int commonPrefixLen = 0;
242 while ( length1 > 0 && length2 > 0 && *s1Char == *s2Char )
252 while ( length1 > 0 && length2 > 0 && s1.at( commonPrefixLen + length1 - 1 ) == s2.at( commonPrefixLen + length2 - 1 ) )
263 else if ( length2 == 0 )
269 if ( length1 > length2 )
272 std::swap( s1Char, s2Char );
273 std::swap( length1, length2 );
277 std::vector< int > col( length2 + 1, 0 );
278 std::vector< int > prevCol( length2 + 1, 0 );
279 std::iota( prevCol.begin(), prevCol.end(), 0 );
281 const QChar *s2start = s2Char;
282 for (
int i = 0; i < length1; ++i )
286 for (
int j = 0; j < length2; ++j )
288 col[j + 1] = std::min( std::min( 1 + col[j], 1 + prevCol[1 + j] ), prevCol[j] + ( ( *s1Char == *s2Char ) ? 0 : 1 ) );
294 return prevCol[length2];
299 if ( string1.isEmpty() || string2.isEmpty() )
306 QString s1( caseSensitive ? string1 : string1.toLower() );
307 QString s2( caseSensitive ? string2 : string2.toLower() );
315 int *currentScores =
new int[s2.length()];
316 int *previousScores =
new int[s2.length()];
317 int maxCommonLength = 0;
318 int lastMaxBeginIndex = 0;
320 const QChar *s1Char = s1.constData();
321 const QChar *s2Char = s2.constData();
322 const QChar *s2Start = s2Char;
324 for (
int i = 0; i < s1.length(); ++i )
326 for (
int j = 0; j < s2.length(); ++j )
328 if ( *s1Char != *s2Char )
330 currentScores[j] = 0;
334 if ( i == 0 || j == 0 )
336 currentScores[j] = 1;
340 currentScores[j] = 1 + previousScores[j - 1];
343 if ( maxCommonLength < currentScores[j] )
345 maxCommonLength = currentScores[j];
346 lastMaxBeginIndex = i;
351 std::swap( currentScores, previousScores );
355 delete[] currentScores;
356 delete[] previousScores;
357 return string1.mid( lastMaxBeginIndex - maxCommonLength + 1, maxCommonLength );
362 if ( string1.isEmpty() && string2.isEmpty() )
368 if ( string1.length() != string2.length() )
375 QString s1( caseSensitive ? string1 : string1.toLower() );
376 QString s2( caseSensitive ? string2 : string2.toLower() );
385 const QChar *s1Char = s1.constData();
386 const QChar *s2Char = s2.constData();
388 for (
int i = 0; i < string1.length(); ++i )
390 if ( *s1Char != *s2Char )
401 if (
string.isEmpty() )
404 QString tmp =
string.toUpper();
407 QChar *char1 = tmp.data();
408 QChar *char2 = tmp.data();
410 for (
int i = 0; i < tmp.length(); ++i, ++char2 )
412 if ( ( *char2 ).unicode() >= 0x41 && ( *char2 ).unicode() <= 0x5A && ( i == 0 || ( ( *char2 ).unicode() != 0x41 && ( *char2 ).unicode() != 0x45
413 && ( *char2 ).unicode() != 0x48 && ( *char2 ).unicode() != 0x49
414 && ( *char2 ).unicode() != 0x4F && ( *char2 ).unicode() != 0x55
415 && ( *char2 ).unicode() != 0x57 && ( *char2 ).unicode() != 0x59 ) ) )
422 tmp.truncate( outLen );
424 QChar *tmpChar = tmp.data();
426 for (
int i = 1; i < tmp.length(); ++i, ++tmpChar )
428 switch ( ( *tmpChar ).unicode() )
434 tmp.replace( i, 1, QChar( 0x31 ) );
445 tmp.replace( i, 1, QChar( 0x32 ) );
450 tmp.replace( i, 1, QChar( 0x33 ) );
454 tmp.replace( i, 1, QChar( 0x34 ) );
459 tmp.replace( i, 1, QChar( 0x35 ) );
463 tmp.replace( i, 1, QChar( 0x36 ) );
473 for (
int i = 1; i < tmp.length(); ++i, ++char2 )
475 if ( *char2 != *char1 )
484 tmp.truncate( outLen );
485 if ( tmp.length() < 4 )
497 QString candidateNormalized = candidate.simplified().normalized( QString::NormalizationForm_C ).toLower();
498 QString searchNormalized = search.simplified().normalized( QString::NormalizationForm_C ).toLower();
500 int candidateLength = candidateNormalized.length();
501 int searchLength = searchNormalized.length();
505 if ( candidateLength == 0 || searchLength == 0 )
508 int candidateIdx = 0;
513 bool isPreviousIndexMatching =
false;
514 bool isWordOpen =
true;
517 while ( candidateIdx < candidateLength )
519 QChar candidateChar = candidateNormalized[candidateIdx++];
520 bool isCandidateCharWordEnd = candidateChar ==
' ' || candidateChar.isPunct();
523 if ( candidateIdx == 1 )
526 else if ( isCandidateCharWordEnd )
533 if ( searchIdx >= searchLength )
536 QChar searchChar = searchNormalized[searchIdx];
537 bool isSearchCharWordEnd = searchChar ==
' ' || searchChar.isPunct();
540 if ( candidateChar == searchChar || ( isCandidateCharWordEnd && isSearchCharWordEnd ) )
545 if ( isSearchCharWordEnd )
549 else if ( isPreviousIndexMatching )
557 else if ( isPreviousIndexMatching )
567 isPreviousIndexMatching =
true;
572 isPreviousIndexMatching =
false;
577 if ( searchIdx >= searchLength )
579 bool isEndOfWord = ( candidateIdx >= candidateLength ) ?
true : candidateNormalized[candidateIdx] ==
' ' || candidateNormalized[candidateIdx].isPunct();
590 if ( searchIdx < searchLength )
593 return static_cast<float>( std::max( score, 0 ) ) / std::max( maxScore, 1 );
599 QString converted = string;
603 const thread_local QRegularExpression urlRegEx(
604 u
"((?:(?:['\"\\(]?http|https|ftp|file)://[^\\s]+[^\\s,.]+)|(?:\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~\\s]|/)))))"_s
606 const thread_local QRegularExpression groupedStringRegEx( u
"^(['\"\\(]+)(.*?)(?:['\")]+)"_s );
607 const thread_local QRegularExpression protoRegEx( u
"^(?:f|ht)tps?://|file://"_s );
608 const thread_local QRegularExpression emailRegEx( u
"([\\w._%+-]+@[\\w.-]+\\.[A-Za-z]+)"_s );
610 std::size_t offset = 0;
612 QRegularExpressionMatch match = urlRegEx.match( converted );
613 while ( match.hasMatch() )
616 QString url = match.captured( 1 );
617 std::size_t urlStart = match.capturedStart( 1 );
619 QString protoUrl = url;
620 const QRegularExpressionMatch groupedStringMatch = groupedStringRegEx.match( protoUrl );
621 if ( groupedStringMatch.hasMatch() )
623 url = groupedStringMatch.captured( 2 );
625 urlStart += groupedStringMatch.capturedLength( 1 );
627 if ( !protoRegEx.match( protoUrl ).hasMatch() )
629 protoUrl.prepend(
"http://" );
631 QString anchor = u
"<a href=\"%1\">%2</a>"_s.arg( protoUrl.toHtmlEscaped(), url.toHtmlEscaped() );
632 converted.replace( urlStart, url.length(), anchor );
633 offset = urlStart + anchor.length();
634 match = urlRegEx.match( converted, offset );
637 match = emailRegEx.match( converted );
638 while ( match.hasMatch() )
641 QString email = match.captured( 1 );
642 QString anchor = u
"<a href=\"mailto:%1\">%1</a>"_s.arg( email.toHtmlEscaped() );
643 converted.replace( match.capturedStart( 1 ), email.length(), anchor );
644 offset = match.capturedStart( 1 ) + anchor.length();
645 match = emailRegEx.match( converted, offset );
656 const thread_local QRegularExpression rxUrl( u
"^(http|https|ftp|file)://\\S+$"_s );
657 return rxUrl.match(
string ).hasMatch();
663 QString converted = html;
664 converted.replace(
"<br>"_L1,
"\n"_L1 );
665 converted.replace(
"<b>"_L1,
"**"_L1 );
666 converted.replace(
"</b>"_L1,
"**"_L1 );
667 converted.replace(
"<pre>"_L1,
"\n```\n"_L1 );
668 converted.replace(
"</pre>"_L1,
"```\n"_L1 );
670 const thread_local QRegularExpression hrefRegEx( u
"<a\\s+href\\s*=\\s*([^<>]*)\\s*>([^<>]*)</a>"_s );
673 QRegularExpressionMatch match = hrefRegEx.match( converted );
674 while ( match.hasMatch() )
676 QString url = match.captured( 1 ).replace(
"\""_L1, QString() );
677 url.replace(
'\'', QString() );
678 QString name = match.captured( 2 );
679 QString anchor = u
"[%1](%2)"_s.arg( name, url );
680 converted.replace( match.capturedStart(), match.capturedLength(), anchor );
681 offset = match.capturedStart() + anchor.length();
682 match = hrefRegEx.match( converted, offset );
688QString
QgsStringUtils::wordWrap(
const QString &
string,
const int length,
const bool useMaxLineLength,
const QString &customDelimiter )
690 if (
string.isEmpty() || length == 0 )
694 QRegularExpression rx;
695 int delimiterLength = 0;
697 if ( !customDelimiter.isEmpty() )
699 rx.setPattern( QRegularExpression::escape( customDelimiter ) );
700 delimiterLength = customDelimiter.length();
705 rx.setPattern( u
"[\\x{200B}\\s]"_s );
709 const QStringList lines =
string.split(
'\n' );
710 int strLength, strCurrent, strHit, lastHit;
712 for (
int i = 0; i < lines.size(); i++ )
714 const QString line = lines.at( i );
715 strLength = line.length();
716 if ( strLength <= length )
719 newstr.append( line );
720 if ( i < lines.size() - 1 )
721 newstr.append(
'\n' );
728 while ( strCurrent < strLength )
732 if ( useMaxLineLength )
735 strHit = ( strCurrent + length >= strLength ) ? -1 : line.lastIndexOf( rx, strCurrent + length );
736 if ( strHit == lastHit || strHit == -1 )
739 strHit = ( strCurrent + std::abs( length ) >= strLength ) ? -1 : line.indexOf( rx, strCurrent + std::abs( length ) );
745 strHit = ( strCurrent + std::abs( length ) >= strLength ) ? -1 : line.indexOf( rx, strCurrent + std::abs( length ) );
749 newstr.append( QStringView { line }.mid( strCurrent, strHit - strCurrent ) );
750 newstr.append(
'\n' );
751 strCurrent = strHit + delimiterLength;
755 newstr.append( QStringView { line }.mid( strCurrent ) );
756 strCurrent = strLength;
759 if ( i < lines.size() - 1 )
760 newstr.append(
'\n' );
768 string =
string.replace(
',', QChar( 65040 ) ).replace( QChar( 8229 ), QChar( 65072 ) );
769 string =
string.replace( QChar( 12289 ), QChar( 65041 ) ).replace( QChar( 12290 ), QChar( 65042 ) );
770 string =
string.replace(
':', QChar( 65043 ) ).replace(
';', QChar( 65044 ) );
771 string =
string.replace(
'!', QChar( 65045 ) ).replace(
'?', QChar( 65046 ) );
772 string =
string.replace( QChar( 12310 ), QChar( 65047 ) ).replace( QChar( 12311 ), QChar( 65048 ) );
773 string =
string.replace( QChar( 8230 ), QChar( 65049 ) );
774 string =
string.replace( QChar( 8212 ), QChar( 65073 ) ).replace( QChar( 8211 ), QChar( 65074 ) );
775 string =
string.replace(
'_', QChar( 65075 ) ).replace( QChar( 65103 ), QChar( 65076 ) );
776 string =
string.replace(
'(', QChar( 65077 ) ).replace(
')', QChar( 65078 ) );
777 string =
string.replace(
'{', QChar( 65079 ) ).replace(
'}', QChar( 65080 ) );
778 string =
string.replace(
'<', QChar( 65087 ) ).replace(
'>', QChar( 65088 ) );
779 string =
string.replace(
'[', QChar( 65095 ) ).replace(
']', QChar( 65096 ) );
780 string =
string.replace( QChar( 12308 ), QChar( 65081 ) ).replace( QChar( 12309 ), QChar( 65082 ) );
781 string =
string.replace( QChar( 12304 ), QChar( 65083 ) ).replace( QChar( 12305 ), QChar( 65084 ) );
782 string =
string.replace( QChar( 12298 ), QChar( 65085 ) ).replace( QChar( 12299 ), QChar( 65086 ) );
783 string =
string.replace( QChar( 12300 ), QChar( 65089 ) ).replace( QChar( 12301 ), QChar( 65090 ) );
784 string =
string.replace( QChar( 12302 ), QChar( 65091 ) ).replace( QChar( 12303 ), QChar( 65092 ) );
791 const QLatin1Char backslash(
'\\' );
792 const int count =
string.count();
795 escaped.reserve( count * 2 );
796 for (
int i = 0; i < count; i++ )
798 switch (
string.at( i ).toLatin1() )
814 escaped.append( backslash );
816 escaped.append(
string.at( i ) );
823 const int charactersToTruncate =
string.length() - maxLength;
824 if ( charactersToTruncate <= 0 )
828 const int truncateFrom =
string.length() / 2 - ( charactersToTruncate + 1 ) / 2;
829 if ( truncateFrom <= 0 )
830 return QChar( 0x2026 );
832 return QStringView(
string ).first( truncateFrom ) + QString( QChar( 0x2026 ) ) + QStringView(
string ).sliced( truncateFrom + charactersToTruncate + 1 );
837 if ( candidate.trimmed().isEmpty() )
840 const thread_local QRegularExpression rxWhitespace( u
"\\s+"_s );
841 const QStringList parts = words.split( rxWhitespace, Qt::SkipEmptyParts );
844 for (
const QString &word : parts )
846 if ( !candidate.contains( word, sensitivity ) )
858 if ( mWholeWordOnly )
860 mRx.setPattern( u
"\\b%1\\b"_s.arg( mMatch ) );
861 mRx.setPatternOptions( mCaseSensitive ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption );
867 QString result = input;
868 if ( !mWholeWordOnly )
870 return result.replace( mMatch, mReplacement, mCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive );
874 return result.replace( mRx, mReplacement );
881 map.insert( u
"match"_s, mMatch );
882 map.insert( u
"replace"_s, mReplacement );
883 map.insert( u
"caseSensitive"_s, mCaseSensitive ? u
"1"_s : u
"0"_s );
884 map.insert( u
"wholeWord"_s, mWholeWordOnly ? u
"1"_s : u
"0"_s );
895 QString result = input;
898 result = r.process( result );
908 QDomElement propEl = doc.createElement( u
"replacement"_s );
909 QgsStringMap::const_iterator it = props.constBegin();
910 for ( ; it != props.constEnd(); ++it )
912 propEl.setAttribute( it.key(), it.value() );
914 elem.appendChild( propEl );
920 mReplacements.clear();
921 QDomNodeList nodelist = elem.elementsByTagName( u
"replacement"_s );
922 for (
int i = 0; i < nodelist.count(); i++ )
924 QDomElement replacementElem = nodelist.at( i ).toElement();
925 QDomNamedNodeMap nodeMap = replacementElem.attributes();
928 for (
int j = 0; j < nodeMap.count(); ++j )
930 props.insert( nodeMap.item( j ).nodeName(), nodeMap.item( j ).nodeValue() );
Capitalization
String capitalization options.
@ AllSmallCaps
Force all characters to small caps.
@ 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.
@ 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.
bool wholeWordOnly() const
Returns true if match only applies to whole words, or false if partial word matches are permitted.
QString replacement() const
Returns the string to replace matches with.
bool caseSensitive() const
Returns true if match is case sensitive.
QgsStringReplacement(const QString &match, const QString &replacement, bool caseSensitive=false, bool wholeWordOnly=false)
Constructor for QgsStringReplacement.
QString match() const
Returns the string matched by this object.
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 QHash< char32_t, QString > createUnaccentMap()
Generates the unaccent mapping table (auto-generated by script at build time).
static QString substituteVerticalCharacters(QString string)
Returns a string with characters having vertical representation form substituted.
static QString createUniqueId(const QString &base=QString())
Generates a unique identifier by appending a random UUID to base.
static QString unaccent(const QString &input)
Removes accents and other diacritical marks from a string, replacing accented characters with their u...
static bool containsByWord(const QString &candidate, const QString &words, Qt::CaseSensitivity sensitivity=Qt::CaseInsensitive)
Given a candidate string, returns true if the candidate contains all the individual words from anothe...
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.
As part of the API refactoring and improvements which landed in the Processing API was substantially reworked from the x version This was done in order to allow much of the underlying Processing framework to be ported into c
QMap< QString, QString > QgsStringMap
#define FUZZY_SCORE_CONSECUTIVE_MATCH
#define FUZZY_SCORE_WORD_MATCH
#define FUZZY_SCORE_NEW_MATCH