QGIS API Documentation 4.5.0-Master (c3bae02b63e)
Loading...
Searching...
No Matches
qgsstringutils.cpp
Go to the documentation of this file.
1/***************************************************************************
2 qgsstringutils.cpp
3 ------------------
4 begin : June 2015
5 copyright : (C) 2015 by Nyall Dawson
6 email : nyall dot dawson at gmail dot com
7 ***************************************************************************
8 * *
9 * This program is free software; you can redistribute it and/or modify *
10 * it under the terms of the GNU General Public License as published by *
11 * the Free Software Foundation; either version 2 of the License, or *
12 * (at your option) any later version. *
13 * *
14 ***************************************************************************/
15
16#include "qgsstringutils.h"
17
18#include <cstdlib>
19#include <numeric>
20
21#include "qgslogger.h"
22
23#include <QRegularExpression>
24#include <QString>
25#include <QStringList>
26#include <QTextBoundaryFinder>
27#include <QUuid>
28#include <QVector>
29
30using namespace Qt::StringLiterals;
31
32QString QgsStringUtils::unaccent( const QString &input )
33{
34 // do a cheap scan ahead first, if all characters are simple ascii characters then we don't have to
35 // do anything
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; } ) )
38 {
39 return input;
40 }
41
42 static const QHash<char32_t, QString> UNACCENT_MAP = QgsStringUtils::createUnaccentMap();
43
44 // Normalize input to NFC so that Unicode characters composed of base +
45 // combining marks are converted to their canonical composed form.
46 // This ensures lookups match the keys in UNACCENT_MAP, which are stored
47 // in NFC (e.g. "e" + U+0301 becomes "é", as PostgreSQL does it.).
48 const QString in = input.normalized( QString::NormalizationForm_C );
49 QString out;
50 out.reserve( in.size() );
51
52 qsizetype i = 0;
53 const qsizetype n = in.size();
54
55 while ( i < n )
56 {
57 const QChar c = in.at( i );
58
59 if ( c.unicode() <= MAX_SIMPLE_CHAR )
60 {
61 // basic ascii character, just skip the costly logic entirely
62 out.append( c );
63 ++i;
64 continue;
65 }
66
67 int len = 1;
68
69 char32_t ucs4 = c.unicode();
70
71 // Detect surrogate pair (non-BMP)
72 if ( c.isHighSurrogate() && i + 1 < n )
73 {
74 const QChar c2 = in.at( i + 1 );
75 if ( c2.isLowSurrogate() )
76 {
77 ucs4 = QChar::surrogateToUcs4( c, c2 );
78 len = 2;
79 }
80 }
81
82 auto it = UNACCENT_MAP.constFind( ucs4 );
83 if ( it != UNACCENT_MAP.constEnd() )
84 {
85 out.append( it.value() );
86 }
87 else
88 {
89 out.append( c );
90 if ( len == 2 )
91 {
92 out.append( in.at( i + 1 ) );
93 }
94 }
95
96 i += len;
97 }
98
99 return out;
100}
101
102QString QgsStringUtils::createUniqueId( const QString &base )
103{
104 // A random UUID guarantees uniqueness; the base is a human-readable prefix.
105 const QString uuid = QUuid::createUuid().toString( QUuid::StringFormat::WithoutBraces );
106 QString id = base.isEmpty() ? uuid : base + '_' + uuid;
107 // Tidy the id up to avoid characters that may cause problems elsewhere (e.g.
108 // in some parts of XML). Replaces every non-word character (word characters
109 // are the alphabet, numbers and underscore) with an underscore.
110 const thread_local QRegularExpression idRx( uR"([\W])"_s );
111 id.replace( idRx, u"_"_s );
112 return id;
113}
114
115QString QgsStringUtils::capitalize( const QString &string, Qgis::Capitalization capitalization )
116{
117 if ( string.isEmpty() )
118 return QString();
119
120 switch ( capitalization )
121 {
124 return string;
125
127 return string.toUpper();
128
131 return string.toLower();
132
134 {
135 QString temp = string;
136
137 QTextBoundaryFinder wordSplitter( QTextBoundaryFinder::Word, string.constData(), string.length(), nullptr, 0 );
138 QTextBoundaryFinder letterSplitter( QTextBoundaryFinder::Grapheme, string.constData(), string.length(), nullptr, 0 );
139
140 wordSplitter.setPosition( 0 );
141 bool first = true;
142 while ( ( first && wordSplitter.boundaryReasons() & QTextBoundaryFinder::StartOfItem ) || wordSplitter.toNextBoundary() >= 0 )
143 {
144 first = false;
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() );
149 }
150 return temp;
151 }
152
154 {
155 // yes, this is MASSIVELY simplifying the problem!!
156
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 );
160
161 const bool allSameCase = string.toLower() == string || string.toUpper() == string;
162 const QStringList parts = ( allSameCase ? string.toLower() : string ).split( splitWords, Qt::SkipEmptyParts );
163 QString result;
164 bool firstWord = true;
165 int i = 0;
166 int lastWord = parts.count() - 1;
167 for ( const QString &word : std::as_const( parts ) )
168 {
169 if ( newPhraseSeparators.contains( word.trimmed() ) )
170 {
171 firstWord = true;
172 result += word;
173 }
174 else if ( firstWord || ( i == lastWord ) || !smallWords.contains( word ) )
175 {
176 result += word.at( 0 ).toUpper() + word.mid( 1 );
177 firstWord = false;
178 }
179 else
180 {
181 result += word;
182 }
183 i++;
184 }
185 return result;
186 }
187
189 QString result = QgsStringUtils::capitalize( string.toLower(), Qgis::Capitalization::ForceFirstLetterToCapital ).simplified();
190 result.remove( ' ' );
191 return result;
192 }
193 // no warnings
194 return string;
195}
196
197// original code from http://www.qtcentre.org/threads/52456-HTML-Unicode-ampersand-encoding
198QString QgsStringUtils::ampersandEncode( const QString &string )
199{
200 QString encoded;
201 for ( int i = 0; i < string.size(); ++i )
202 {
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 += "&amp;"_L1;
208 else if ( ch.unicode() == 60 )
209 encoded += "&lt;"_L1;
210 else if ( ch.unicode() == 62 )
211 encoded += "&gt;"_L1;
212 else
213 encoded += ch;
214 }
215 return encoded;
216}
217
218int QgsStringUtils::levenshteinDistance( const QString &string1, const QString &string2, bool caseSensitive )
219{
220 int length1 = string1.length();
221 int length2 = string2.length();
222
223 //empty strings? solution is trivial...
224 if ( string1.isEmpty() )
225 {
226 return length2;
227 }
228 else if ( string2.isEmpty() )
229 {
230 return length1;
231 }
232
233 //handle case sensitive flag (or not)
234 QString s1( caseSensitive ? string1 : string1.toLower() );
235 QString s2( caseSensitive ? string2 : string2.toLower() );
236
237 const QChar *s1Char = s1.constData();
238 const QChar *s2Char = s2.constData();
239
240 //strip out any common prefix
241 int commonPrefixLen = 0;
242 while ( length1 > 0 && length2 > 0 && *s1Char == *s2Char )
243 {
244 commonPrefixLen++;
245 length1--;
246 length2--;
247 s1Char++;
248 s2Char++;
249 }
250
251 //strip out any common suffix
252 while ( length1 > 0 && length2 > 0 && s1.at( commonPrefixLen + length1 - 1 ) == s2.at( commonPrefixLen + length2 - 1 ) )
253 {
254 length1--;
255 length2--;
256 }
257
258 //fully checked either string? if so, the answer is easy...
259 if ( length1 == 0 )
260 {
261 return length2;
262 }
263 else if ( length2 == 0 )
264 {
265 return length1;
266 }
267
268 //ensure the inner loop is longer
269 if ( length1 > length2 )
270 {
271 std::swap( s1, s2 );
272 std::swap( s1Char, s2Char );
273 std::swap( length1, length2 );
274 }
275
276 //levenshtein algorithm begins here
277 std::vector< int > col( length2 + 1, 0 );
278 std::vector< int > prevCol( length2 + 1, 0 );
279 std::iota( prevCol.begin(), prevCol.end(), 0 );
280
281 const QChar *s2start = s2Char;
282 for ( int i = 0; i < length1; ++i )
283 {
284 col[0] = i + 1;
285 s2Char = s2start;
286 for ( int j = 0; j < length2; ++j )
287 {
288 col[j + 1] = std::min( std::min( 1 + col[j], 1 + prevCol[1 + j] ), prevCol[j] + ( ( *s1Char == *s2Char ) ? 0 : 1 ) );
289 s2Char++;
290 }
291 col.swap( prevCol );
292 s1Char++;
293 }
294 return prevCol[length2];
295}
296
297QString QgsStringUtils::longestCommonSubstring( const QString &string1, const QString &string2, bool caseSensitive )
298{
299 if ( string1.isEmpty() || string2.isEmpty() )
300 {
301 //empty strings, solution is trivial...
302 return QString();
303 }
304
305 //handle case sensitive flag (or not)
306 QString s1( caseSensitive ? string1 : string1.toLower() );
307 QString s2( caseSensitive ? string2 : string2.toLower() );
308
309 if ( s1 == s2 )
310 {
311 //another trivial case, identical strings
312 return s1;
313 }
314
315 int *currentScores = new int[s2.length()];
316 int *previousScores = new int[s2.length()];
317 int maxCommonLength = 0;
318 int lastMaxBeginIndex = 0;
319
320 const QChar *s1Char = s1.constData();
321 const QChar *s2Char = s2.constData();
322 const QChar *s2Start = s2Char;
323
324 for ( int i = 0; i < s1.length(); ++i )
325 {
326 for ( int j = 0; j < s2.length(); ++j )
327 {
328 if ( *s1Char != *s2Char )
329 {
330 currentScores[j] = 0;
331 }
332 else
333 {
334 if ( i == 0 || j == 0 )
335 {
336 currentScores[j] = 1;
337 }
338 else
339 {
340 currentScores[j] = 1 + previousScores[j - 1];
341 }
342
343 if ( maxCommonLength < currentScores[j] )
344 {
345 maxCommonLength = currentScores[j];
346 lastMaxBeginIndex = i;
347 }
348 }
349 s2Char++;
350 }
351 std::swap( currentScores, previousScores );
352 s1Char++;
353 s2Char = s2Start;
354 }
355 delete[] currentScores;
356 delete[] previousScores;
357 return string1.mid( lastMaxBeginIndex - maxCommonLength + 1, maxCommonLength );
358}
359
360int QgsStringUtils::hammingDistance( const QString &string1, const QString &string2, bool caseSensitive )
361{
362 if ( string1.isEmpty() && string2.isEmpty() )
363 {
364 //empty strings, solution is trivial...
365 return 0;
366 }
367
368 if ( string1.length() != string2.length() )
369 {
370 //invalid inputs
371 return -1;
372 }
373
374 //handle case sensitive flag (or not)
375 QString s1( caseSensitive ? string1 : string1.toLower() );
376 QString s2( caseSensitive ? string2 : string2.toLower() );
377
378 if ( s1 == s2 )
379 {
380 //another trivial case, identical strings
381 return 0;
382 }
383
384 int distance = 0;
385 const QChar *s1Char = s1.constData();
386 const QChar *s2Char = s2.constData();
387
388 for ( int i = 0; i < string1.length(); ++i )
389 {
390 if ( *s1Char != *s2Char )
391 distance++;
392 s1Char++;
393 s2Char++;
394 }
395
396 return distance;
397}
398
399QString QgsStringUtils::soundex( const QString &string )
400{
401 if ( string.isEmpty() )
402 return QString();
403
404 QString tmp = string.toUpper();
405
406 //strip non character codes, and vowel like characters after the first character
407 QChar *char1 = tmp.data();
408 QChar *char2 = tmp.data();
409 int outLen = 0;
410 for ( int i = 0; i < tmp.length(); ++i, ++char2 )
411 {
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 ) ) )
416 {
417 *char1 = *char2;
418 char1++;
419 outLen++;
420 }
421 }
422 tmp.truncate( outLen );
423
424 QChar *tmpChar = tmp.data();
425 tmpChar++;
426 for ( int i = 1; i < tmp.length(); ++i, ++tmpChar )
427 {
428 switch ( ( *tmpChar ).unicode() )
429 {
430 case 0x42:
431 case 0x46:
432 case 0x50:
433 case 0x56:
434 tmp.replace( i, 1, QChar( 0x31 ) );
435 break;
436
437 case 0x43:
438 case 0x47:
439 case 0x4A:
440 case 0x4B:
441 case 0x51:
442 case 0x53:
443 case 0x58:
444 case 0x5A:
445 tmp.replace( i, 1, QChar( 0x32 ) );
446 break;
447
448 case 0x44:
449 case 0x54:
450 tmp.replace( i, 1, QChar( 0x33 ) );
451 break;
452
453 case 0x4C:
454 tmp.replace( i, 1, QChar( 0x34 ) );
455 break;
456
457 case 0x4D:
458 case 0x4E:
459 tmp.replace( i, 1, QChar( 0x35 ) );
460 break;
461
462 case 0x52:
463 tmp.replace( i, 1, QChar( 0x36 ) );
464 break;
465 }
466 }
467
468 //remove adjacent duplicates
469 char1 = tmp.data();
470 char2 = tmp.data();
471 char2++;
472 outLen = 1;
473 for ( int i = 1; i < tmp.length(); ++i, ++char2 )
474 {
475 if ( *char2 != *char1 )
476 {
477 char1++;
478 *char1 = *char2;
479 outLen++;
480 if ( outLen == 4 )
481 break;
482 }
483 }
484 tmp.truncate( outLen );
485 if ( tmp.length() < 4 )
486 {
487 tmp.append( "000" );
488 tmp.truncate( 4 );
489 }
490
491 return tmp;
492}
493
494
495double QgsStringUtils::fuzzyScore( const QString &candidate, const QString &search )
496{
497 QString candidateNormalized = candidate.simplified().normalized( QString::NormalizationForm_C ).toLower();
498 QString searchNormalized = search.simplified().normalized( QString::NormalizationForm_C ).toLower();
499
500 int candidateLength = candidateNormalized.length();
501 int searchLength = searchNormalized.length();
502 int score = 0;
503
504 // if the candidate and the search term are empty, no other option than 0 score
505 if ( candidateLength == 0 || searchLength == 0 )
506 return score;
507
508 int candidateIdx = 0;
509 int searchIdx = 0;
510 // there is always at least one word
511 int maxScore = FUZZY_SCORE_WORD_MATCH;
512
513 bool isPreviousIndexMatching = false;
514 bool isWordOpen = true;
515
516 // loop trough each candidate char and calculate the potential max score
517 while ( candidateIdx < candidateLength )
518 {
519 QChar candidateChar = candidateNormalized[candidateIdx++];
520 bool isCandidateCharWordEnd = candidateChar == ' ' || candidateChar.isPunct();
521
522 // the first char is always the default score
523 if ( candidateIdx == 1 )
524 maxScore += FUZZY_SCORE_NEW_MATCH;
525 // every space character or underscore is a opportunity for a new word
526 else if ( isCandidateCharWordEnd )
527 maxScore += FUZZY_SCORE_WORD_MATCH;
528 // potentially we can match every other character
529 else
531
532 // we looped through all the characters
533 if ( searchIdx >= searchLength )
534 continue;
535
536 QChar searchChar = searchNormalized[searchIdx];
537 bool isSearchCharWordEnd = searchChar == ' ' || searchChar.isPunct();
538
539 // match!
540 if ( candidateChar == searchChar || ( isCandidateCharWordEnd && isSearchCharWordEnd ) )
541 {
542 searchIdx++;
543
544 // if we have just successfully finished a word, give higher score
545 if ( isSearchCharWordEnd )
546 {
547 if ( isWordOpen )
548 score += FUZZY_SCORE_WORD_MATCH;
549 else if ( isPreviousIndexMatching )
551 else
552 score += FUZZY_SCORE_NEW_MATCH;
553
554 isWordOpen = true;
555 }
556 // if we have consecutive characters matching, give higher score
557 else if ( isPreviousIndexMatching )
558 {
560 }
561 // normal score for new independent character that matches
562 else
563 {
564 score += FUZZY_SCORE_NEW_MATCH;
565 }
566
567 isPreviousIndexMatching = true;
568 }
569 // if the current character does NOT match, we are sure we cannot build a word for now
570 else
571 {
572 isPreviousIndexMatching = false;
573 isWordOpen = false;
574 }
575
576 // if the search string is covered, check if the last match is end of word
577 if ( searchIdx >= searchLength )
578 {
579 bool isEndOfWord = ( candidateIdx >= candidateLength ) ? true : candidateNormalized[candidateIdx] == ' ' || candidateNormalized[candidateIdx].isPunct();
580
581 if ( isEndOfWord )
582 score += FUZZY_SCORE_WORD_MATCH;
583 }
584
585 // QgsLogger::debug( u"TMP: %1 | %2 | %3 | %4 | %5"_s.arg( candidateChar, searchChar, QString::number(score), QString::number(isCandidateCharWordEnd), QString::number(isSearchCharWordEnd) ) + QStringLiteral( __FILE__ ) );
586 }
587
588 // QgsLogger::debug( u"RES: %1 | %2"_s.arg( QString::number(maxScore), QString::number(score) ) + QStringLiteral( __FILE__ ) );
589 // we didn't loop through all the search chars, it means, that they are not present in the current candidate
590 if ( searchIdx < searchLength )
591 score = 0;
592
593 return static_cast<float>( std::max( score, 0 ) ) / std::max( maxScore, 1 );
594}
595
596
597QString QgsStringUtils::insertLinks( const QString &string, bool *foundLinks )
598{
599 QString converted = string;
600
601 // http://alanstorm.com/url_regex_explained
602 // note - there's more robust implementations available
603 const thread_local QRegularExpression urlRegEx(
604 u"((?:(?:['\"\\(]?http|https|ftp|file)://[^\\s]+[^\\s,.]+)|(?:\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~\\s]|/)))))"_s
605 );
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 );
609
610 std::size_t offset = 0;
611 bool found = false;
612 QRegularExpressionMatch match = urlRegEx.match( converted );
613 while ( match.hasMatch() )
614 {
615 found = true;
616 QString url = match.captured( 1 );
617 std::size_t urlStart = match.capturedStart( 1 );
618
619 QString protoUrl = url;
620 const QRegularExpressionMatch groupedStringMatch = groupedStringRegEx.match( protoUrl );
621 if ( groupedStringMatch.hasMatch() )
622 {
623 url = groupedStringMatch.captured( 2 );
624 protoUrl = url;
625 urlStart += groupedStringMatch.capturedLength( 1 );
626 }
627 if ( !protoRegEx.match( protoUrl ).hasMatch() )
628 {
629 protoUrl.prepend( "http://" );
630 }
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 );
635 }
636
637 match = emailRegEx.match( converted );
638 while ( match.hasMatch() )
639 {
640 found = true;
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 );
646 }
647
648 if ( foundLinks )
649 *foundLinks = found;
650
651 return converted;
652}
653
654bool QgsStringUtils::isUrl( const QString &string )
655{
656 const thread_local QRegularExpression rxUrl( u"^(http|https|ftp|file)://\\S+$"_s );
657 return rxUrl.match( string ).hasMatch();
658}
659
660QString QgsStringUtils::htmlToMarkdown( const QString &html )
661{
662 // Any changes in this function must be copied to qgscrashreport.cpp too
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 );
669
670 const thread_local QRegularExpression hrefRegEx( u"<a\\s+href\\s*=\\s*([^<>]*)\\s*>([^<>]*)</a>"_s );
671
672 int offset = 0;
673 QRegularExpressionMatch match = hrefRegEx.match( converted );
674 while ( match.hasMatch() )
675 {
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 );
683 }
684
685 return converted;
686}
687
688QString QgsStringUtils::wordWrap( const QString &string, const int length, const bool useMaxLineLength, const QString &customDelimiter )
689{
690 if ( string.isEmpty() || length == 0 )
691 return string;
692
693 QString newstr;
694 QRegularExpression rx;
695 int delimiterLength = 0;
696
697 if ( !customDelimiter.isEmpty() )
698 {
699 rx.setPattern( QRegularExpression::escape( customDelimiter ) );
700 delimiterLength = customDelimiter.length();
701 }
702 else
703 {
704 // \x{200B} is a ZERO-WIDTH SPACE, needed for worwrap to support a number of complex scripts (Indic, Arabic, etc.)
705 rx.setPattern( u"[\\x{200B}\\s]"_s );
706 delimiterLength = 1;
707 }
708
709 const QStringList lines = string.split( '\n' );
710 int strLength, strCurrent, strHit, lastHit;
711
712 for ( int i = 0; i < lines.size(); i++ )
713 {
714 const QString line = lines.at( i );
715 strLength = line.length();
716 if ( strLength <= length )
717 {
718 // shortcut, no wrapping required
719 newstr.append( line );
720 if ( i < lines.size() - 1 )
721 newstr.append( '\n' );
722 continue;
723 }
724 strCurrent = 0;
725 strHit = 0;
726 lastHit = 0;
727
728 while ( strCurrent < strLength )
729 {
730 // positive wrap value = desired maximum line width to wrap
731 // negative wrap value = desired minimum line width before wrap
732 if ( useMaxLineLength )
733 {
734 //first try to locate delimiter backwards
735 strHit = ( strCurrent + length >= strLength ) ? -1 : line.lastIndexOf( rx, strCurrent + length );
736 if ( strHit == lastHit || strHit == -1 )
737 {
738 //if no new backward delimiter found, try to locate forward
739 strHit = ( strCurrent + std::abs( length ) >= strLength ) ? -1 : line.indexOf( rx, strCurrent + std::abs( length ) );
740 }
741 lastHit = strHit;
742 }
743 else
744 {
745 strHit = ( strCurrent + std::abs( length ) >= strLength ) ? -1 : line.indexOf( rx, strCurrent + std::abs( length ) );
746 }
747 if ( strHit > -1 )
748 {
749 newstr.append( QStringView { line }.mid( strCurrent, strHit - strCurrent ) );
750 newstr.append( '\n' );
751 strCurrent = strHit + delimiterLength;
752 }
753 else
754 {
755 newstr.append( QStringView { line }.mid( strCurrent ) );
756 strCurrent = strLength;
757 }
758 }
759 if ( i < lines.size() - 1 )
760 newstr.append( '\n' );
761 }
762
763 return newstr;
764}
765
767{
768 string = string.replace( ',', QChar( 65040 ) ).replace( QChar( 8229 ), QChar( 65072 ) ); // comma & two-dot leader
769 string = string.replace( QChar( 12289 ), QChar( 65041 ) ).replace( QChar( 12290 ), QChar( 65042 ) ); // ideographic comma & full stop
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 ) ); // white lenticular brackets
773 string = string.replace( QChar( 8230 ), QChar( 65049 ) ); // three-dot ellipse
774 string = string.replace( QChar( 8212 ), QChar( 65073 ) ).replace( QChar( 8211 ), QChar( 65074 ) ); // em & en dash
775 string = string.replace( '_', QChar( 65075 ) ).replace( QChar( 65103 ), QChar( 65076 ) ); // low line & wavy low line
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 ) ); // tortoise shell brackets
781 string = string.replace( QChar( 12304 ), QChar( 65083 ) ).replace( QChar( 12305 ), QChar( 65084 ) ); // black lenticular brackets
782 string = string.replace( QChar( 12298 ), QChar( 65085 ) ).replace( QChar( 12299 ), QChar( 65086 ) ); // double angle brackets
783 string = string.replace( QChar( 12300 ), QChar( 65089 ) ).replace( QChar( 12301 ), QChar( 65090 ) ); // corner brackets
784 string = string.replace( QChar( 12302 ), QChar( 65091 ) ).replace( QChar( 12303 ), QChar( 65092 ) ); // white corner brackets
785 return string;
786}
787
788QString QgsStringUtils::qRegExpEscape( const QString &string )
789{
790 // code and logic taken from the Qt source code
791 const QLatin1Char backslash( '\\' );
792 const int count = string.count();
793
794 QString escaped;
795 escaped.reserve( count * 2 );
796 for ( int i = 0; i < count; i++ )
797 {
798 switch ( string.at( i ).toLatin1() )
799 {
800 case '$':
801 case '(':
802 case ')':
803 case '*':
804 case '+':
805 case '.':
806 case '?':
807 case '[':
808 case '\\':
809 case ']':
810 case '^':
811 case '{':
812 case '|':
813 case '}':
814 escaped.append( backslash );
815 }
816 escaped.append( string.at( i ) );
817 }
818 return escaped;
819}
820
821QString QgsStringUtils::truncateMiddleOfString( const QString &string, int maxLength )
822{
823 const int charactersToTruncate = string.length() - maxLength;
824 if ( charactersToTruncate <= 0 )
825 return string;
826
827 // note we actually truncate an extra character, as we'll be replacing it with the ... character
828 const int truncateFrom = string.length() / 2 - ( charactersToTruncate + 1 ) / 2;
829 if ( truncateFrom <= 0 )
830 return QChar( 0x2026 );
831
832 return QStringView( string ).first( truncateFrom ) + QString( QChar( 0x2026 ) ) + QStringView( string ).sliced( truncateFrom + charactersToTruncate + 1 );
833}
834
835bool QgsStringUtils::containsByWord( const QString &candidate, const QString &words, Qt::CaseSensitivity sensitivity )
836{
837 if ( candidate.trimmed().isEmpty() )
838 return false;
839
840 const thread_local QRegularExpression rxWhitespace( u"\\s+"_s );
841 const QStringList parts = words.split( rxWhitespace, Qt::SkipEmptyParts );
842 if ( parts.empty() )
843 return false;
844 for ( const QString &word : parts )
845 {
846 if ( !candidate.contains( word, sensitivity ) )
847 return false;
848 }
849 return true;
850}
851
853 : mMatch( match )
854 , mReplacement( replacement )
855 , mCaseSensitive( caseSensitive )
856 , mWholeWordOnly( wholeWordOnly )
857{
858 if ( mWholeWordOnly )
859 {
860 mRx.setPattern( u"\\b%1\\b"_s.arg( mMatch ) );
861 mRx.setPatternOptions( mCaseSensitive ? QRegularExpression::NoPatternOption : QRegularExpression::CaseInsensitiveOption );
862 }
863}
864
865QString QgsStringReplacement::process( const QString &input ) const
866{
867 QString result = input;
868 if ( !mWholeWordOnly )
869 {
870 return result.replace( mMatch, mReplacement, mCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive );
871 }
872 else
873 {
874 return result.replace( mRx, mReplacement );
875 }
876}
877
879{
880 QgsStringMap map;
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 );
885 return map;
886}
887
889{
890 return QgsStringReplacement( properties.value( u"match"_s ), properties.value( u"replace"_s ), properties.value( u"caseSensitive"_s, u"0"_s ) == "1"_L1, properties.value( u"wholeWord"_s, u"0"_s ) == "1"_L1 );
891}
892
893QString QgsStringReplacementCollection::process( const QString &input ) const
894{
895 QString result = input;
896 for ( const QgsStringReplacement &r : mReplacements )
897 {
898 result = r.process( result );
899 }
900 return result;
901}
902
903void QgsStringReplacementCollection::writeXml( QDomElement &elem, QDomDocument &doc ) const
904{
905 for ( const QgsStringReplacement &r : mReplacements )
906 {
907 QgsStringMap props = r.properties();
908 QDomElement propEl = doc.createElement( u"replacement"_s );
909 QgsStringMap::const_iterator it = props.constBegin();
910 for ( ; it != props.constEnd(); ++it )
911 {
912 propEl.setAttribute( it.key(), it.value() );
913 }
914 elem.appendChild( propEl );
915 }
916}
917
918void QgsStringReplacementCollection::readXml( const QDomElement &elem )
919{
920 mReplacements.clear();
921 QDomNodeList nodelist = elem.elementsByTagName( u"replacement"_s );
922 for ( int i = 0; i < nodelist.count(); i++ )
923 {
924 QDomElement replacementElem = nodelist.at( i ).toElement();
925 QDomNamedNodeMap nodeMap = replacementElem.attributes();
926
927 QgsStringMap props;
928 for ( int j = 0; j < nodeMap.count(); ++j )
929 {
930 props.insert( nodeMap.item( j ).nodeName(), nodeMap.item( j ).nodeValue() );
931 }
932 mReplacements << QgsStringReplacement::fromProperties( props );
933 }
934}
Capitalization
String capitalization options.
Definition qgis.h:3654
@ AllSmallCaps
Force all characters to small caps.
Definition qgis.h:3662
@ MixedCase
Mixed case, ie no change.
Definition qgis.h:3655
@ UpperCamelCase
Convert the string to upper camel case. Note that this method does not unaccent characters.
Definition qgis.h:3661
@ AllLowercase
Convert all characters to lowercase.
Definition qgis.h:3657
@ TitleCase
Simple title case conversion - does not fully grammatically parse the text and uses simple rules only...
Definition qgis.h:3660
@ SmallCaps
Mixed case small caps.
Definition qgis.h:3659
@ ForceFirstLetterToCapital
Convert just the first letter of each word to uppercase, leave the rest untouched.
Definition qgis.h:3658
@ AllUppercase
Convert all characters to uppercase.
Definition qgis.h:3656
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
Definition qgis.h:8433
#define FUZZY_SCORE_CONSECUTIVE_MATCH
#define FUZZY_SCORE_WORD_MATCH
#define FUZZY_SCORE_NEW_MATCH