QGIS API Documentation  3.14.0-Pi (9f7028fd23)
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 #include "qgslogger.h"
18 #include <QVector>
19 #include <QRegExp>
20 #include <QStringList>
21 #include <QTextBoundaryFinder>
22 #include <QRegularExpression>
23 #include <cstdlib> // for std::abs
24 
25 QString QgsStringUtils::capitalize( const QString &string, QgsStringUtils::Capitalization capitalization )
26 {
27  if ( string.isEmpty() )
28  return QString();
29 
30  switch ( capitalization )
31  {
32  case MixedCase:
33  return string;
34 
35  case AllUppercase:
36  return string.toUpper();
37 
38  case AllLowercase:
39  return string.toLower();
40 
42  {
43  QString temp = string;
44 
45  QTextBoundaryFinder wordSplitter( QTextBoundaryFinder::Word, string.constData(), string.length(), nullptr, 0 );
46  QTextBoundaryFinder letterSplitter( QTextBoundaryFinder::Grapheme, string.constData(), string.length(), nullptr, 0 );
47 
48  wordSplitter.setPosition( 0 );
49  bool first = true;
50  while ( ( first && wordSplitter.boundaryReasons() & QTextBoundaryFinder::StartOfItem )
51  || wordSplitter.toNextBoundary() >= 0 )
52  {
53  first = false;
54  letterSplitter.setPosition( wordSplitter.position() );
55  letterSplitter.toNextBoundary();
56  QString substr = string.mid( wordSplitter.position(), letterSplitter.position() - wordSplitter.position() );
57  temp.replace( wordSplitter.position(), substr.length(), substr.toUpper() );
58  }
59  return temp;
60  }
61 
62  case TitleCase:
63  {
64  // yes, this is MASSIVELY simplifying the problem!!
65 
66  static QStringList smallWords;
67  static QStringList newPhraseSeparators;
68  static QRegularExpression splitWords;
69  if ( smallWords.empty() )
70  {
71  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( '|' );
72  newPhraseSeparators = QObject::tr( ".|:" ).split( '|' );
73  splitWords = QRegularExpression( QStringLiteral( "\\b" ), QRegularExpression::UseUnicodePropertiesOption );
74  }
75 
76  const QStringList parts = string.split( splitWords, QString::SkipEmptyParts );
77  QString result;
78  bool firstWord = true;
79  int i = 0;
80  int lastWord = parts.count() - 1;
81  for ( const QString &word : qgis::as_const( parts ) )
82  {
83  if ( newPhraseSeparators.contains( word.trimmed() ) )
84  {
85  firstWord = true;
86  result += word;
87  }
88  else if ( firstWord || ( i == lastWord ) || !smallWords.contains( word ) )
89  {
90  result += word.at( 0 ).toUpper() + word.mid( 1 );
91  firstWord = false;
92  }
93  else
94  {
95  result += word;
96  }
97  i++;
98  }
99  return result;
100  }
101 
102  case UpperCamelCase:
103  QString result = QgsStringUtils::capitalize( string.toLower(), QgsStringUtils::ForceFirstLetterToCapital ).simplified();
104  result.remove( ' ' );
105  return result;
106  }
107  // no warnings
108  return string;
109 }
110 
111 // original code from http://www.qtcentre.org/threads/52456-HTML-Unicode-ampersand-encoding
112 QString QgsStringUtils::ampersandEncode( const QString &string )
113 {
114  QString encoded;
115  for ( int i = 0; i < string.size(); ++i )
116  {
117  QChar ch = string.at( i );
118  if ( ch.unicode() > 160 )
119  encoded += QStringLiteral( "&#%1;" ).arg( static_cast< int >( ch.unicode() ) );
120  else if ( ch.unicode() == 38 )
121  encoded += QStringLiteral( "&amp;" );
122  else if ( ch.unicode() == 60 )
123  encoded += QStringLiteral( "&lt;" );
124  else if ( ch.unicode() == 62 )
125  encoded += QStringLiteral( "&gt;" );
126  else
127  encoded += ch;
128  }
129  return encoded;
130 }
131 
132 int QgsStringUtils::levenshteinDistance( const QString &string1, const QString &string2, bool caseSensitive )
133 {
134  int length1 = string1.length();
135  int length2 = string2.length();
136 
137  //empty strings? solution is trivial...
138  if ( string1.isEmpty() )
139  {
140  return length2;
141  }
142  else if ( string2.isEmpty() )
143  {
144  return length1;
145  }
146 
147  //handle case sensitive flag (or not)
148  QString s1( caseSensitive ? string1 : string1.toLower() );
149  QString s2( caseSensitive ? string2 : string2.toLower() );
150 
151  const QChar *s1Char = s1.constData();
152  const QChar *s2Char = s2.constData();
153 
154  //strip out any common prefix
155  int commonPrefixLen = 0;
156  while ( length1 > 0 && length2 > 0 && *s1Char == *s2Char )
157  {
158  commonPrefixLen++;
159  length1--;
160  length2--;
161  s1Char++;
162  s2Char++;
163  }
164 
165  //strip out any common suffix
166  while ( length1 > 0 && length2 > 0 && s1.at( commonPrefixLen + length1 - 1 ) == s2.at( commonPrefixLen + length2 - 1 ) )
167  {
168  length1--;
169  length2--;
170  }
171 
172  //fully checked either string? if so, the answer is easy...
173  if ( length1 == 0 )
174  {
175  return length2;
176  }
177  else if ( length2 == 0 )
178  {
179  return length1;
180  }
181 
182  //ensure the inner loop is longer
183  if ( length1 > length2 )
184  {
185  std::swap( s1, s2 );
186  std::swap( length1, length2 );
187  }
188 
189  //levenshtein algorithm begins here
190  QVector< int > col;
191  col.fill( 0, length2 + 1 );
192  QVector< int > prevCol;
193  prevCol.reserve( length2 + 1 );
194  for ( int i = 0; i < length2 + 1; ++i )
195  {
196  prevCol << i;
197  }
198  const QChar *s2start = s2Char;
199  for ( int i = 0; i < length1; ++i )
200  {
201  col[0] = i + 1;
202  s2Char = s2start;
203  for ( int j = 0; j < length2; ++j )
204  {
205  col[j + 1] = std::min( std::min( 1 + col[j], 1 + prevCol[1 + j] ), prevCol[j] + ( ( *s1Char == *s2Char ) ? 0 : 1 ) );
206  s2Char++;
207  }
208  col.swap( prevCol );
209  s1Char++;
210  }
211  return prevCol[length2];
212 }
213 
214 QString QgsStringUtils::longestCommonSubstring( const QString &string1, const QString &string2, bool caseSensitive )
215 {
216  if ( string1.isEmpty() || string2.isEmpty() )
217  {
218  //empty strings, solution is trivial...
219  return QString();
220  }
221 
222  //handle case sensitive flag (or not)
223  QString s1( caseSensitive ? string1 : string1.toLower() );
224  QString s2( caseSensitive ? string2 : string2.toLower() );
225 
226  if ( s1 == s2 )
227  {
228  //another trivial case, identical strings
229  return s1;
230  }
231 
232  int *currentScores = new int [ s2.length()];
233  int *previousScores = new int [ s2.length()];
234  int maxCommonLength = 0;
235  int lastMaxBeginIndex = 0;
236 
237  const QChar *s1Char = s1.constData();
238  const QChar *s2Char = s2.constData();
239  const QChar *s2Start = s2Char;
240 
241  for ( int i = 0; i < s1.length(); ++i )
242  {
243  for ( int j = 0; j < s2.length(); ++j )
244  {
245  if ( *s1Char != *s2Char )
246  {
247  currentScores[j] = 0;
248  }
249  else
250  {
251  if ( i == 0 || j == 0 )
252  {
253  currentScores[j] = 1;
254  }
255  else
256  {
257  currentScores[j] = 1 + previousScores[j - 1];
258  }
259 
260  if ( maxCommonLength < currentScores[j] )
261  {
262  maxCommonLength = currentScores[j];
263  lastMaxBeginIndex = i;
264  }
265  }
266  s2Char++;
267  }
268  std::swap( currentScores, previousScores );
269  s1Char++;
270  s2Char = s2Start;
271  }
272  delete [] currentScores;
273  delete [] previousScores;
274  return string1.mid( lastMaxBeginIndex - maxCommonLength + 1, maxCommonLength );
275 }
276 
277 int QgsStringUtils::hammingDistance( const QString &string1, const QString &string2, bool caseSensitive )
278 {
279  if ( string1.isEmpty() && string2.isEmpty() )
280  {
281  //empty strings, solution is trivial...
282  return 0;
283  }
284 
285  if ( string1.length() != string2.length() )
286  {
287  //invalid inputs
288  return -1;
289  }
290 
291  //handle case sensitive flag (or not)
292  QString s1( caseSensitive ? string1 : string1.toLower() );
293  QString s2( caseSensitive ? string2 : string2.toLower() );
294 
295  if ( s1 == s2 )
296  {
297  //another trivial case, identical strings
298  return 0;
299  }
300 
301  int distance = 0;
302  const QChar *s1Char = s1.constData();
303  const QChar *s2Char = s2.constData();
304 
305  for ( int i = 0; i < string1.length(); ++i )
306  {
307  if ( *s1Char != *s2Char )
308  distance++;
309  s1Char++;
310  s2Char++;
311  }
312 
313  return distance;
314 }
315 
316 QString QgsStringUtils::soundex( const QString &string )
317 {
318  if ( string.isEmpty() )
319  return QString();
320 
321  QString tmp = string.toUpper();
322 
323  //strip non character codes, and vowel like characters after the first character
324  QChar *char1 = tmp.data();
325  QChar *char2 = tmp.data();
326  int outLen = 0;
327  for ( int i = 0; i < tmp.length(); ++i, ++char2 )
328  {
329  if ( ( *char2 ).unicode() >= 0x41 && ( *char2 ).unicode() <= 0x5A && ( i == 0 || ( ( *char2 ).unicode() != 0x41 && ( *char2 ).unicode() != 0x45
330  && ( *char2 ).unicode() != 0x48 && ( *char2 ).unicode() != 0x49
331  && ( *char2 ).unicode() != 0x4F && ( *char2 ).unicode() != 0x55
332  && ( *char2 ).unicode() != 0x57 && ( *char2 ).unicode() != 0x59 ) ) )
333  {
334  *char1 = *char2;
335  char1++;
336  outLen++;
337  }
338  }
339  tmp.truncate( outLen );
340 
341  QChar *tmpChar = tmp.data();
342  tmpChar++;
343  for ( int i = 1; i < tmp.length(); ++i, ++tmpChar )
344  {
345  switch ( ( *tmpChar ).unicode() )
346  {
347  case 0x42:
348  case 0x46:
349  case 0x50:
350  case 0x56:
351  tmp.replace( i, 1, QChar( 0x31 ) );
352  break;
353 
354  case 0x43:
355  case 0x47:
356  case 0x4A:
357  case 0x4B:
358  case 0x51:
359  case 0x53:
360  case 0x58:
361  case 0x5A:
362  tmp.replace( i, 1, QChar( 0x32 ) );
363  break;
364 
365  case 0x44:
366  case 0x54:
367  tmp.replace( i, 1, QChar( 0x33 ) );
368  break;
369 
370  case 0x4C:
371  tmp.replace( i, 1, QChar( 0x34 ) );
372  break;
373 
374  case 0x4D:
375  case 0x4E:
376  tmp.replace( i, 1, QChar( 0x35 ) );
377  break;
378 
379  case 0x52:
380  tmp.replace( i, 1, QChar( 0x36 ) );
381  break;
382  }
383  }
384 
385  //remove adjacent duplicates
386  char1 = tmp.data();
387  char2 = tmp.data();
388  char2++;
389  outLen = 1;
390  for ( int i = 1; i < tmp.length(); ++i, ++char2 )
391  {
392  if ( *char2 != *char1 )
393  {
394  char1++;
395  *char1 = *char2;
396  outLen++;
397  if ( outLen == 4 )
398  break;
399  }
400  }
401  tmp.truncate( outLen );
402  if ( tmp.length() < 4 )
403  {
404  tmp.append( "000" );
405  tmp.truncate( 4 );
406  }
407 
408  return tmp;
409 }
410 
411 
412 double QgsStringUtils::fuzzyScore( const QString &candidate, const QString &search )
413 {
414  QString candidateNormalized = candidate.simplified().normalized( QString:: NormalizationForm_C ).toLower();
415  QString searchNormalized = search.simplified().normalized( QString:: NormalizationForm_C ).toLower();
416 
417  int candidateLength = candidateNormalized.length();
418  int searchLength = searchNormalized.length();
419  int score = 0;
420 
421  // if the candidate and the search term are empty, no other option than 0 score
422  if ( candidateLength == 0 || searchLength == 0 )
423  return score;
424 
425  int candidateIdx = 0;
426  int searchIdx = 0;
427  // there is always at least one word
428  int maxScore = FUZZY_SCORE_WORD_MATCH;
429 
430  bool isPreviousIndexMatching = false;
431  bool isWordOpen = true;
432 
433  // loop trough each candidate char and calculate the potential max score
434  while ( candidateIdx < candidateLength )
435  {
436  QChar candidateChar = candidateNormalized[ candidateIdx++ ];
437  bool isCandidateCharWordEnd = candidateChar == ' ' || candidateChar.isPunct();
438 
439  // the first char is always the default score
440  if ( candidateIdx == 1 )
441  maxScore += FUZZY_SCORE_NEW_MATCH;
442  // every space character or underscore is a opportunity for a new word
443  else if ( isCandidateCharWordEnd )
444  maxScore += FUZZY_SCORE_WORD_MATCH;
445  // potentially we can match every other character
446  else
447  maxScore += FUZZY_SCORE_CONSECUTIVE_MATCH;
448 
449  // we looped through all the characters
450  if ( searchIdx >= searchLength )
451  continue;
452 
453  QChar searchChar = searchNormalized[ searchIdx ];
454  bool isSearchCharWordEnd = searchChar == ' ' || searchChar.isPunct();
455 
456  // match!
457  if ( candidateChar == searchChar || ( isCandidateCharWordEnd && isSearchCharWordEnd ) )
458  {
459  searchIdx++;
460 
461  // if we have just successfully finished a word, give higher score
462  if ( isSearchCharWordEnd )
463  {
464  if ( isWordOpen )
465  score += FUZZY_SCORE_WORD_MATCH;
466  else if ( isPreviousIndexMatching )
468  else
469  score += FUZZY_SCORE_NEW_MATCH;
470 
471  isWordOpen = true;
472  }
473  // if we have consecutive characters matching, give higher score
474  else if ( isPreviousIndexMatching )
475  {
477  }
478  // normal score for new independent character that matches
479  else
480  {
481  score += FUZZY_SCORE_NEW_MATCH;
482  }
483 
484  isPreviousIndexMatching = true;
485  }
486  // if the current character does NOT match, we are sure we cannot build a word for now
487  else
488  {
489  isPreviousIndexMatching = false;
490  isWordOpen = false;
491  }
492 
493  // if the search string is covered, check if the last match is end of word
494  if ( searchIdx >= searchLength )
495  {
496  bool isEndOfWord = ( candidateIdx >= candidateLength )
497  ? true
498  : candidateNormalized[candidateIdx] == ' ' || candidateNormalized[candidateIdx].isPunct();
499 
500  if ( isEndOfWord )
501  score += FUZZY_SCORE_WORD_MATCH;
502  }
503 
504  // QgsLogger::debug( QStringLiteral( "TMP: %1 | %2 | %3 | %4 | %5" ).arg( candidateChar, searchChar, QString::number(score), QString::number(isCandidateCharWordEnd), QString::number(isSearchCharWordEnd) ) + QStringLiteral( __FILE__ ) );
505  }
506 
507  // QgsLogger::debug( QStringLiteral( "RES: %1 | %2" ).arg( QString::number(maxScore), QString::number(score) ) + QStringLiteral( __FILE__ ) );
508  // we didn't loop through all the search chars, it means, that they are not present in the current candidate
509  if ( searchIdx < searchLength )
510  score = 0;
511 
512  return static_cast<float>( std::max( score, 0 ) ) / std::max( maxScore, 1 );
513 }
514 
515 
516 QString QgsStringUtils::insertLinks( const QString &string, bool *foundLinks )
517 {
518  QString converted = string;
519 
520  // http://alanstorm.com/url_regex_explained
521  // note - there's more robust implementations available, but we need one which works within the limitation of QRegExp
522  static QRegExp urlRegEx( "(\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^!\"#$%&'()*+,\\-./:;<=>?@[\\\\\\]^_`{|}~\\s]|/))))" );
523  static QRegExp protoRegEx( "^(?:f|ht)tps?://|file://" );
524  static QRegExp emailRegEx( "([\\w._%+-]+@[\\w.-]+\\.[A-Za-z]+)" );
525 
526  int offset = 0;
527  bool found = false;
528  while ( urlRegEx.indexIn( converted, offset ) != -1 )
529  {
530  found = true;
531  QString url = urlRegEx.cap( 1 );
532  QString protoUrl = url;
533  if ( protoRegEx.indexIn( protoUrl ) == -1 )
534  {
535  protoUrl.prepend( "http://" );
536  }
537  QString anchor = QStringLiteral( "<a href=\"%1\">%2</a>" ).arg( protoUrl.toHtmlEscaped(), url.toHtmlEscaped() );
538  converted.replace( urlRegEx.pos( 1 ), url.length(), anchor );
539  offset = urlRegEx.pos( 1 ) + anchor.length();
540  }
541  offset = 0;
542  while ( emailRegEx.indexIn( converted, offset ) != -1 )
543  {
544  found = true;
545  QString email = emailRegEx.cap( 1 );
546  QString anchor = QStringLiteral( "<a href=\"mailto:%1\">%1</a>" ).arg( email.toHtmlEscaped() );
547  converted.replace( emailRegEx.pos( 1 ), email.length(), anchor );
548  offset = emailRegEx.pos( 1 ) + anchor.length();
549  }
550 
551  if ( foundLinks )
552  *foundLinks = found;
553 
554  return converted;
555 }
556 
557 QString QgsStringUtils::htmlToMarkdown( const QString &html )
558 {
559  // Any changes in this function must be copied to qgscrashreport.cpp too
560  QString converted = html;
561  converted.replace( QLatin1String( "<br>" ), QLatin1String( "\n" ) );
562  converted.replace( QLatin1String( "<b>" ), QLatin1String( "**" ) );
563  converted.replace( QLatin1String( "</b>" ), QLatin1String( "**" ) );
564 
565  static QRegExp hrefRegEx( "<a\\s+href\\s*=\\s*([^<>]*)\\s*>([^<>]*)</a>" );
566  int offset = 0;
567  while ( hrefRegEx.indexIn( converted, offset ) != -1 )
568  {
569  QString url = hrefRegEx.cap( 1 ).replace( QStringLiteral( "\"" ), QString() );
570  url.replace( '\'', QString() );
571  QString name = hrefRegEx.cap( 2 );
572  QString anchor = QStringLiteral( "[%1](%2)" ).arg( name, url );
573  converted.replace( hrefRegEx, anchor );
574  offset = hrefRegEx.pos( 1 ) + anchor.length();
575  }
576 
577  return converted;
578 }
579 
580 QString QgsStringUtils::wordWrap( const QString &string, const int length, const bool useMaxLineLength, const QString &customDelimiter )
581 {
582  if ( string.isEmpty() || length == 0 )
583  return string;
584 
585  QString newstr;
586  QRegExp rx;
587  int delimiterLength = 0;
588 
589  if ( !customDelimiter.isEmpty() )
590  {
591  rx.setPatternSyntax( QRegExp::FixedString );
592  rx.setPattern( customDelimiter );
593  delimiterLength = customDelimiter.length();
594  }
595  else
596  {
597  // \x200B is a ZERO-WIDTH SPACE, needed for worwrap to support a number of complex scripts (Indic, Arabic, etc.)
598  rx.setPattern( QStringLiteral( "[\\s\\x200B]" ) );
599  delimiterLength = 1;
600  }
601 
602  const QStringList lines = string.split( '\n' );
603  int strLength, strCurrent, strHit, lastHit;
604 
605  for ( int i = 0; i < lines.size(); i++ )
606  {
607  strLength = lines.at( i ).length();
608  strCurrent = 0;
609  strHit = 0;
610  lastHit = 0;
611 
612  while ( strCurrent < strLength )
613  {
614  // positive wrap value = desired maximum line width to wrap
615  // negative wrap value = desired minimum line width before wrap
616  if ( useMaxLineLength )
617  {
618  //first try to locate delimiter backwards
619  strHit = lines.at( i ).lastIndexOf( rx, strCurrent + length );
620  if ( strHit == lastHit || strHit == -1 )
621  {
622  //if no new backward delimiter found, try to locate forward
623  strHit = lines.at( i ).indexOf( rx, strCurrent + std::abs( length ) );
624  }
625  lastHit = strHit;
626  }
627  else
628  {
629  strHit = lines.at( i ).indexOf( rx, strCurrent + std::abs( length ) );
630  }
631  if ( strHit > -1 )
632  {
633  newstr.append( lines.at( i ).midRef( strCurrent, strHit - strCurrent ) );
634  newstr.append( '\n' );
635  strCurrent = strHit + delimiterLength;
636  }
637  else
638  {
639  newstr.append( lines.at( i ).midRef( strCurrent ) );
640  strCurrent = strLength;
641  }
642  }
643  if ( i < lines.size() - 1 )
644  newstr.append( '\n' );
645  }
646 
647  return newstr;
648 }
649 
651 {
652  string = string.replace( ',', QChar( 65040 ) ).replace( QChar( 8229 ), QChar( 65072 ) ); // comma & two-dot leader
653  string = string.replace( QChar( 12289 ), QChar( 65041 ) ).replace( QChar( 12290 ), QChar( 65042 ) ); // ideographic comma & full stop
654  string = string.replace( ':', QChar( 65043 ) ).replace( ';', QChar( 65044 ) );
655  string = string.replace( '!', QChar( 65045 ) ).replace( '?', QChar( 65046 ) );
656  string = string.replace( QChar( 12310 ), QChar( 65047 ) ).replace( QChar( 12311 ), QChar( 65048 ) ); // white lenticular brackets
657  string = string.replace( QChar( 8230 ), QChar( 65049 ) ); // three-dot ellipse
658  string = string.replace( QChar( 8212 ), QChar( 65073 ) ).replace( QChar( 8211 ), QChar( 65074 ) ); // em & en dash
659  string = string.replace( '_', QChar( 65075 ) ).replace( QChar( 65103 ), QChar( 65076 ) ); // low line & wavy low line
660  string = string.replace( '(', QChar( 65077 ) ).replace( ')', QChar( 65078 ) );
661  string = string.replace( '{', QChar( 65079 ) ).replace( '}', QChar( 65080 ) );
662  string = string.replace( '<', QChar( 65087 ) ).replace( '>', QChar( 65088 ) );
663  string = string.replace( '[', QChar( 65095 ) ).replace( ']', QChar( 65096 ) );
664  string = string.replace( QChar( 12308 ), QChar( 65081 ) ).replace( QChar( 12309 ), QChar( 65082 ) ); // tortoise shell brackets
665  string = string.replace( QChar( 12304 ), QChar( 65083 ) ).replace( QChar( 12305 ), QChar( 65084 ) ); // black lenticular brackets
666  string = string.replace( QChar( 12298 ), QChar( 65085 ) ).replace( QChar( 12299 ), QChar( 65086 ) ); // double angle brackets
667  string = string.replace( QChar( 12300 ), QChar( 65089 ) ).replace( QChar( 12301 ), QChar( 65090 ) ); // corner brackets
668  string = string.replace( QChar( 12302 ), QChar( 65091 ) ).replace( QChar( 12303 ), QChar( 65092 ) ); // white corner brackets
669  return string;
670 }
671 
672 QgsStringReplacement::QgsStringReplacement( const QString &match, const QString &replacement, bool caseSensitive, bool wholeWordOnly )
673  : mMatch( match )
674  , mReplacement( replacement )
675  , mCaseSensitive( caseSensitive )
676  , mWholeWordOnly( wholeWordOnly )
677 {
678  if ( mWholeWordOnly )
679  mRx = QRegExp( QString( "\\b%1\\b" ).arg( mMatch ),
680  mCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive );
681 }
682 
683 QString QgsStringReplacement::process( const QString &input ) const
684 {
685  QString result = input;
686  if ( !mWholeWordOnly )
687  {
688  return result.replace( mMatch, mReplacement, mCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive );
689  }
690  else
691  {
692  return result.replace( mRx, mReplacement );
693  }
694 }
695 
697 {
698  QgsStringMap map;
699  map.insert( QStringLiteral( "match" ), mMatch );
700  map.insert( QStringLiteral( "replace" ), mReplacement );
701  map.insert( QStringLiteral( "caseSensitive" ), mCaseSensitive ? "1" : "0" );
702  map.insert( QStringLiteral( "wholeWord" ), mWholeWordOnly ? "1" : "0" );
703  return map;
704 }
705 
707 {
708  return QgsStringReplacement( properties.value( QStringLiteral( "match" ) ),
709  properties.value( QStringLiteral( "replace" ) ),
710  properties.value( QStringLiteral( "caseSensitive" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ),
711  properties.value( QStringLiteral( "wholeWord" ), QStringLiteral( "0" ) ) == QLatin1String( "1" ) );
712 }
713 
714 QString QgsStringReplacementCollection::process( const QString &input ) const
715 {
716  QString result = input;
717  const auto constMReplacements = mReplacements;
718  for ( const QgsStringReplacement &r : constMReplacements )
719  {
720  result = r.process( result );
721  }
722  return result;
723 }
724 
725 void QgsStringReplacementCollection::writeXml( QDomElement &elem, QDomDocument &doc ) const
726 {
727  const auto constMReplacements = mReplacements;
728  for ( const QgsStringReplacement &r : constMReplacements )
729  {
730  QgsStringMap props = r.properties();
731  QDomElement propEl = doc.createElement( QStringLiteral( "replacement" ) );
732  QgsStringMap::const_iterator it = props.constBegin();
733  for ( ; it != props.constEnd(); ++it )
734  {
735  propEl.setAttribute( it.key(), it.value() );
736  }
737  elem.appendChild( propEl );
738  }
739 }
740 
741 void QgsStringReplacementCollection::readXml( const QDomElement &elem )
742 {
743  mReplacements.clear();
744  QDomNodeList nodelist = elem.elementsByTagName( QStringLiteral( "replacement" ) );
745  for ( int i = 0; i < nodelist.count(); i++ )
746  {
747  QDomElement replacementElem = nodelist.at( i ).toElement();
748  QDomNamedNodeMap nodeMap = replacementElem.attributes();
749 
750  QgsStringMap props;
751  for ( int j = 0; j < nodeMap.count(); ++j )
752  {
753  props.insert( nodeMap.item( j ).nodeName(), nodeMap.item( j ).nodeValue() );
754  }
755  mReplacements << QgsStringReplacement::fromProperties( props );
756  }
757 
758 }
QgsStringUtils::UpperCamelCase
@ UpperCamelCase
Convert the string to upper camel case. Note that this method does not unaccent characters.
Definition: qgsstringutils.h:195
QgsStringUtils::insertLinks
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 ....
Definition: qgsstringutils.cpp:516
QgsStringReplacementCollection::readXml
void readXml(const QDomElement &elem)
Reads the collection state from an XML element.
Definition: qgsstringutils.cpp:741
qgsstringutils.h
QgsStringUtils::ampersandEncode
static QString ampersandEncode(const QString &string)
Makes a raw string safe for inclusion as a HTML/XML string literal.
Definition: qgsstringutils.cpp:112
QgsStringUtils::hammingDistance
static int hammingDistance(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the Hamming distance between two strings.
Definition: qgsstringutils.cpp:277
FUZZY_SCORE_WORD_MATCH
#define FUZZY_SCORE_WORD_MATCH
Definition: qgsstringutils.h:27
QgsStringUtils::Capitalization
Capitalization
Capitalization options.
Definition: qgsstringutils.h:188
QgsStringReplacement::process
QString process(const QString &input) const
Processes a given input string, applying any valid replacements which should be made.
Definition: qgsstringutils.cpp:683
QgsStringUtils::MixedCase
@ MixedCase
Mixed case, ie no change.
Definition: qgsstringutils.h:190
QgsStringUtils::substituteVerticalCharacters
static QString substituteVerticalCharacters(QString string)
Returns a string with characters having vertical representation form substituted.
Definition: qgsstringutils.cpp:650
QgsStringReplacementCollection::process
QString process(const QString &input) const
Processes a given input string, applying any valid replacements which should be made using QgsStringR...
Definition: qgsstringutils.cpp:714
QgsStringUtils::AllLowercase
@ AllLowercase
Convert all characters to lowercase.
Definition: qgsstringutils.h:192
QgsStringReplacement
A representation of a single string replacement.
Definition: qgsstringutils.h:38
QgsStringUtils::fuzzyScore
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.
Definition: qgsstringutils.cpp:412
QgsStringUtils::capitalize
static QString capitalize(const QString &string, Capitalization capitalization)
Converts a string by applying capitalization rules to the string.
Definition: qgsstringutils.cpp:25
QgsStringReplacement::QgsStringReplacement
QgsStringReplacement(const QString &match, const QString &replacement, bool caseSensitive=false, bool wholeWordOnly=false)
Constructor for QgsStringReplacement.
Definition: qgsstringutils.cpp:672
QgsStringUtils::TitleCase
@ TitleCase
Simple title case conversion - does not fully grammatically parse the text and uses simple rules only...
Definition: qgsstringutils.h:194
QgsStringUtils::soundex
static QString soundex(const QString &string)
Returns the Soundex representation of a string.
Definition: qgsstringutils.cpp:316
QgsStringMap
QMap< QString, QString > QgsStringMap
Definition: qgis.h:714
QgsStringUtils::ForceFirstLetterToCapital
@ ForceFirstLetterToCapital
Convert just the first letter of each word to uppercase, leave the rest untouched.
Definition: qgsstringutils.h:193
QgsStringUtils::wordWrap
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.
Definition: qgsstringutils.cpp:580
FUZZY_SCORE_NEW_MATCH
#define FUZZY_SCORE_NEW_MATCH
Definition: qgsstringutils.h:28
QgsStringUtils::levenshteinDistance
static int levenshteinDistance(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the Levenshtein edit distance between two strings.
Definition: qgsstringutils.cpp:132
QgsStringReplacement::fromProperties
static QgsStringReplacement fromProperties(const QgsStringMap &properties)
Creates a new QgsStringReplacement from an encoded properties map.
Definition: qgsstringutils.cpp:706
QgsStringReplacementCollection::writeXml
void writeXml(QDomElement &elem, QDomDocument &doc) const
Writes the collection state to an XML element.
Definition: qgsstringutils.cpp:725
qgslogger.h
FUZZY_SCORE_CONSECUTIVE_MATCH
#define FUZZY_SCORE_CONSECUTIVE_MATCH
Definition: qgsstringutils.h:29
QgsStringReplacement::properties
QgsStringMap properties() const
Returns a map of the replacement properties.
Definition: qgsstringutils.cpp:696
QgsStringUtils::AllUppercase
@ AllUppercase
Convert all characters to uppercase.
Definition: qgsstringutils.h:191
QgsStringUtils::htmlToMarkdown
static QString htmlToMarkdown(const QString &html)
Convert simple HTML to markdown.
Definition: qgsstringutils.cpp:557
QgsStringUtils::longestCommonSubstring
static QString longestCommonSubstring(const QString &string1, const QString &string2, bool caseSensitive=false)
Returns the longest common substring between two strings.
Definition: qgsstringutils.cpp:214