stringOps.H
Go to the documentation of this file.
1 /*---------------------------------------------------------------------------*\
2  ========= |
3  \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4  \\ / O peration |
5  \\ / A nd | www.openfoam.com
6  \\/ M anipulation |
7 -------------------------------------------------------------------------------
8  Copyright (C) 2011-2012 OpenFOAM Foundation
9  Copyright (C) 2016-2021 OpenCFD Ltd.
10 -------------------------------------------------------------------------------
11 License
12  This file is part of OpenFOAM.
13 
14  OpenFOAM is free software: you can redistribute it and/or modify it
15  under the terms of the GNU General Public License as published by
16  the Free Software Foundation, either version 3 of the License, or
17  (at your option) any later version.
18 
19  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
20  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22  for more details.
23 
24  You should have received a copy of the GNU General Public License
25  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
26 
27 Namespace
28  Foam::stringOps
29 
30 Description
31  Collection of static functions for various string-related operations
32 
33 SourceFiles
34  stringOps.C
35  stringOpsTemplates.C
36 
37 \*---------------------------------------------------------------------------*/
38 
39 #ifndef stringOps_H
40 #define stringOps_H
41 
42 #include "scalar.H"
43 #include "string.H"
44 #include "SubStrings.H"
45 #include "word.H"
46 #include "dictionary.H"
47 #include "HashTable.H"
48 #include "stringOpsSort.H"
49 #include "stringOpsEvaluate.H"
50 #include "wordRes.H"
51 #include <utility>
52 
53 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
54 
55 namespace Foam
56 {
57 
58 // Forward Declarations
59 class OSstream;
60 template<class T1, class T2> class Tuple2;
61 
62 /*---------------------------------------------------------------------------*\
63  Namespace stringOps Declaration
64 \*---------------------------------------------------------------------------*/
65 
66 namespace stringOps
67 {
68  //- Count the number of occurrences of the specified character
69  std::string::size_type count(const std::string& s, const char c);
70 
71  //- Count the number of occurrences of the specified character
72  // Correctly handles nullptr.
73  std::string::size_type count(const char* s, const char c);
74 
75  //- Return true if text matches one of the regular expressions.
76  inline bool match(const UList<wordRe>& patterns, const std::string& text)
77  {
78  return wordRes::matcher(patterns)(text);
79  }
80 
81  //- Quote any meta-characters in given string
82  template<class StringType, class UnaryPredicate>
83  StringType quotemeta
84  (
85  const StringType& str,
86  const UnaryPredicate& meta,
87  const char quote = '\\'
88  );
89 
90  //- Expand occurrences of variables according to the mapping
91  //- and return the expanded string.
92  //
93  // \sa stringOps::inplaceExpand() for details
94  string expand
95  (
96  const std::string& s,
97  const HashTable<string>& mapping,
98  const char sigil = '$'
99  );
100 
101  //- Inplace expand occurrences of variables according to the mapping.
102  //- Does \b not use environment values.
103  //
104  // Expansion includes:
105  // -# Variables
106  // - \c $VAR
107  // - \c ${VAR}
108  //
109  // -# Default and alternative values as per the POSIX shell:
110  // - \c ${parameter:-defValue}
111  // If parameter is unset or null, the \c defValue is substituted.
112  // Otherwise, the value of parameter is substituted.
113  // - \c ${parameter:+altValue}
114  // If parameter is unset or null, nothing is substituted.
115  // Otherwise the \c altValue is substituted.
116  // .
117  //
118  // General behaviour:
119  // - Unknown entries are removed silently.
120  // - Malformed entries (eg, brace mismatch, sigil followed by unknown
121  // characters) are left as is.
122  //
123  // \param[in,out] s The string to modify inplace.
124  // \param mapping The lookup table
125  // \param sigil The leading sigil. Can be changed to avoid conflict
126  // with other string expansions. (default: '$')
127  //
128  // \par Expansion behaviour
129  // - alternatives = True
130  // - environment = False
131  // - allow empty = True
132  // - subDict = Not applicable
133  // .
134  //
135  // \note Currently only used by Foam::dynamicCode.
136  void inplaceExpand
137  (
138  std::string& s,
139  const HashTable<string>& mapping,
140  const char sigil = '$'
141  );
142 
143 
144  //- Inplace expand occurrences of variables according to the dictionary
145  //- and (optionally) environment variables.
146  //
147  // Expansion includes:
148  // -# Dictionary variables and (optionally) environment variables
149  // - \c $VAR
150  // - \c ${VAR}
151  // - \c ${VAR:-defValue}
152  // - \c ${VAR:+altValue}
153  // -# Mathematical evaluation using stringOps::evaluate
154  // - \c ${{EXPR}}
155  // -# Current directory
156  // - leading "./"
157  // : the current directory - Foam::cwd()
158  // -# Leading tag expansion for commonly used directories
159  // - <b> <etc>/ </b>
160  // : user/group/other OpenFOAM etc directory
161  // - <b> <etc:</b><em>[ugoa]+</em>)<b>>/ </b>
162  // : user/group/other etc with specified location mode
163  // - <b> <case>/ </b>
164  // : The \c $FOAM_CASE directory
165  // - <b> <constant>/ </b>
166  // : The \c $FOAM_CASE/constant directory
167  // - <b> <system>/ </b>
168  // : The \c $FOAM_CASE/system directory
169  // -# Tilde expansion
170  // - leading "~/" : home directory
171  // - leading "~user" : home directory for specified user
172  // -# Default and alternative values as per the POSIX shell:
173  // - \c ${parameter:-defValue}
174  // If parameter is unset or null, the \c defValue is substituted.
175  // Otherwise, the value of parameter is substituted.
176  // - \c ${parameter:+altValue}
177  // If parameter is unset or null, nothing is substituted.
178  // Otherwise the \c altValue is substituted.
179  // .
180  //
181  // General behaviour:
182  // - Malformed entries (eg, brace mismatch, sigil followed by unknown
183  // characters) are left as is.
184  // - Supports recursive variable expansions.
185  // For example, "${var${num}}" and "${{100 + ${var}}}"
186  //
187  // \param[in,out] s The string to modify inplace
188  // \param dict The dictionary context for the expansion
189  // \param allowEnv Allow use of environment values as fallback
190  // \param allowEmpty Allow empty expansions, or treat as Fatal
191  // \param allowSubDict Allow expansion of subDict entries as well as
192  // primitive entries (default: false)
193  // \param sigil The leading sigil. Can be changed to avoid conflict
194  // with other string expansions. (default: '$')
195  //
196  // \sa Foam::findEtcEntry(), Foam::findEtcEntries(), stringOps::evaluate()
197  //
198  // \par Expansion behaviour
199  // - alternatives = True
200  // - environment = Given by parameter
201  // - allow empty = Given by parameter
202  // - subDict = Given by parameter (default: False)
203  // .
204  //
205  // \note This function has too many parameters and should generally
206  // be avoided in user coding.
207  void inplaceExpand
208  (
209  std::string& s,
210  const dictionary& dict,
211  const bool allowEnv,
212  const bool allowEmpty,
213  const bool allowSubDict = false,
214  const char sigil = '$'
215  );
216 
217 
218  //- Expand occurrences of dictionary or environment variables.
219  //
220  // Empty expansions are allowed.
221  // Serialization of subDict entries is permitted.
222  //
223  // \sa stringOps::inplaceExpand(std::string&, const dictionary&, char)
224  string expand
225  (
226  const std::string& s,
227  const dictionary& dict,
228  const char sigil = '$'
229  );
230 
231  //- Inplace expand occurrences of dictionary or environment variables.
232  //
233  // Empty expansions are allowed.
234  // Serialization of subDict entries is permitted.
235  //
236  // \sa
237  // stringOps::inplaceExpand
238  // (std::string&, const dictionary&, bool, bool, bool, char)
239  //
240  // \par Expansion behaviour
241  // - alternatives = True
242  // - environment = True
243  // - allow empty = True
244  // - subDict = True
245  // .
246  void inplaceExpand
247  (
248  std::string& s,
249  const dictionary& dict,
250  const char sigil = '$'
251  );
252 
253 
254  //- Expand initial tags, tildes, and all occurrences of environment
255  //- variables.
256  //
257  // \sa
258  // stringOps::inplaceExpand(std::string&, bool);
259  string expand(const std::string& s, const bool allowEmpty = false);
260 
261 
262  //- Expand initial tags, tildes, and all occurrences of environment
263  //- variables
264  //
265  // The expansion behaviour is identical to
266  // stringOps::inplaceExpand
267  // (std::string&, const dictionary&, bool, bool, bool, char)
268  // except that there is no dictionary and the environment variables
269  // are always enabled.
270  //
271  // \par Expansion behaviour
272  // - alternatives = True
273  // - environment = True
274  // - allow empty = Given by parameter (default: False)
275  // - subDict = Not applicable
276  // .
277  void inplaceExpand(std::string& s, const bool allowEmpty = false);
278 
279 
280  //- Replace environment variable contents with its name.
281  // This is essentially the inverse operation for inplaceExpand
282  // for a single element.
283  // Return true if a replacement was successful.
284  bool inplaceReplaceVar(std::string& s, const word& varName);
285 
286  //- Return a copy of the input string with validated characters
287  template<class StringType, class UnaryPredicate>
288  StringType validate
289  (
290  const std::string& str,
291  const UnaryPredicate& accept,
292  const bool invert=false
293  );
294 
295  //- Find (first, last) non-space locations in string or sub-string.
296  // This may change to std::string_view in the future.
297  std::pair<size_t, size_t>
298  findTrim
299  (
300  const std::string& s,
301  size_t pos = 0,
302  size_t len = std::string::npos
303  );
304 
305  //- Return string trimmed of leading whitespace
306  string trimLeft(const std::string& s);
307 
308  //- Trim leading whitespace inplace
309  void inplaceTrimLeft(std::string& s);
310 
311  //- Return string trimmed of trailing whitespace
312  string trimRight(const std::string& s);
313 
314  //- Trim trailing whitespace inplace
315  void inplaceTrimRight(std::string& s);
316 
317  //- Return string trimmed of leading and trailing whitespace
318  string trim(const std::string& s);
319 
320  //- Trim leading and trailing whitespace inplace
321  void inplaceTrim(std::string& s);
322 
323  //- Eliminate whitespace inplace
324  void inplaceRemoveSpace(std::string& s);
325 
326 
327  //- Return string with C/C++ comments removed
328  string removeComments(const std::string& s);
329 
330  //- Remove C/C++ comments inplace
331  void inplaceRemoveComments(std::string& s);
332 
333 
334  //- Return string copy transformed with std::tolower on each character
335  string lower(const std::string& s);
336 
337  //- Inplace transform string with std::tolower on each character
338  void inplaceLower(std::string& s);
339 
340  //- Return string copy transformed with std::toupper on each character
341  string upper(const std::string& s);
342 
343  //- Inplace transform string with std::toupper on each character
344  void inplaceUpper(std::string& s);
345 
346  //- Split out arguments (named or unnamed) from an input string.
347  //
348  // For example,
349  // \verbatim
350  // (U)
351  // -> named = ()
352  // -> unnamed = (U)
353  //
354  // (patch=inlet, p)
355  // -> named = ((patch inlet))
356  // -> unnamed = (p)
357  //
358  // testing, start=100, stop=200
359  // -> named = ((start 100)(stop 200))
360  // -> unnamed = (testing)
361  // \endverbatim
362  //
363  // \return total number of arguments
364  label splitFunctionArgs
365  (
366  const std::string& str,
367  wordRes& args,
368  List<Tuple2<word, string>>& namedArgs
369  );
370 
371  //- Split string into sub-strings at the delimiter character.
372  // Empty sub-strings are normally suppressed.
373  // Behaviour is ill-defined if delim is a NUL character.
374  template<class StringType>
376  (
377  const StringType& str,
378  const char delim,
379  const bool keepEmpty = false
380  );
381 
382  //- Split string into sub-strings using delimiter string.
383  // Empty sub-strings are normally suppressed.
384  template<class StringType>
386  (
387  const StringType& str,
388  const std::string& delim,
389  const bool keepEmpty = false
390  );
391 
392  //- Split string into sub-strings using any characters in delimiter.
393  // Empty sub-strings are normally suppressed.
394  // Behaviour is ill-defined if delim is an empty string.
395  template<class StringType>
397  (
398  const StringType& str,
399  const std::string& delim
400  );
401 
402  //- Split string into sub-strings using a fixed field width.
403  // Behaviour is ill-defined if width is zero.
404  // \param str the string to be split
405  // \param width the fixed field width for each sub-string
406  // \param start the optional offset of where to start the splitting.
407  // Any text prior to start is ignored in the operation.
408  template<class StringType>
410  (
411  const StringType& str,
412  const std::string::size_type width,
413  const std::string::size_type start = 0
414  );
415 
416  //- Split string into sub-strings at whitespace (TAB, NL, VT, FF, CR, SPC)
417  // Empty sub-strings are suppressed.
418  template<class StringType>
420  (
421  const StringType& str
422  );
423 
424  //- Output string with text wrapping.
425  // Always includes a trailing newline, unless the string itself is empty.
426  //
427  // \param os the output stream
428  // \param str the text to be output
429  // \param width the max-width before wrapping
430  // \param indent indentation for continued lines
431  // \param escape escape any backslashes on output
432  void writeWrapped
433  (
434  OSstream& os,
435  const std::string& str,
436  const std::string::size_type width,
437  const std::string::size_type indent = 0,
438  const bool escape = false
439  );
440 
441 } // End namespace stringOps
442 
443 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
444 
445 } // End namespace Foam
446 
447 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
448 
449 #ifdef NoRepository
450  #include "stringOpsTemplates.C"
451 #endif
452 
453 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
454 
455 #endif
456 
457 // ************************************************************************* //
stringOpsEvaluate.H
String expression evaluation.
wordRes.H
Foam::stringOps::inplaceTrimRight
void inplaceTrimRight(std::string &s)
Trim trailing whitespace inplace.
Definition: stringOps.C:992
Foam::word
A class for handling words, derived from Foam::string.
Definition: word.H:65
HashTable.H
s
gmvFile<< "tracers "<< particles.size()<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().x()<< " ";}gmvFile<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().y()<< " ";}gmvFile<< nl;for(const passiveParticle &p :particles){ gmvFile<< p.position().z()<< " ";}gmvFile<< nl;forAll(lagrangianScalarNames, i){ word name=lagrangianScalarNames[i];IOField< scalar > s(IOobject(name, runTime.timeName(), cloud::prefix, mesh, IOobject::MUST_READ, IOobject::NO_WRITE))
Definition: gmvOutputSpray.H:25
Foam::stringOps::writeWrapped
void writeWrapped(OSstream &os, const std::string &str, const std::string::size_type width, const std::string::size_type indent=0, const bool escape=false)
Output string with text wrapping.
Definition: stringOps.C:1217
stringOpsSort.H
Specialized string sorting.
Foam::stringOps::inplaceTrim
void inplaceTrim(std::string &s)
Trim leading and trailing whitespace inplace.
Definition: stringOps.C:1067
Foam::stringOps::inplaceReplaceVar
bool inplaceReplaceVar(std::string &s, const word &varName)
Replace environment variable contents with its name.
Definition: stringOps.C:906
Foam::stringOps::split
Foam::SubStrings< StringType > split(const StringType &str, const char delim, const bool keepEmpty=false)
Split string into sub-strings at the delimiter character.
Definition: stringOpsTemplates.C:98
stringOpsTemplates.C
Foam::stringOps::trim
string trim(const std::string &s)
Return string trimmed of leading and trailing whitespace.
Definition: stringOps.C:1046
string.H
Foam::stringOps::splitSpace
Foam::SubStrings< StringType > splitSpace(const StringType &str)
Split string into sub-strings at whitespace (TAB, NL, VT, FF, CR, SPC)
Definition: stringOpsTemplates.C:246
Foam::stringOps::trimLeft
string trimLeft(const std::string &s)
Return string trimmed of leading whitespace.
Definition: stringOps.C:930
Foam::SubStrings
Sub-ranges of a string with a structure similar to std::match_results, but without the underlying reg...
Definition: CStringList.H:63
Foam::stringOps::inplaceRemoveComments
void inplaceRemoveComments(std::string &s)
Remove C/C++ comments inplace.
Definition: stringOps.C:1088
Foam::invert
labelList invert(const label len, const labelUList &map)
Create an inverse one-to-one mapping.
Definition: ListOps.C:36
Foam::stringOps::inplaceExpand
void inplaceExpand(std::string &s, const HashTable< string > &mapping, const char sigil='$')
Definition: stringOps.C:731
Foam::stringOps::lower
string lower(const std::string &s)
Return string copy transformed with std::tolower on each character.
Definition: stringOps.C:1184
Foam::stringOps::quotemeta
StringType quotemeta(const StringType &str, const UnaryPredicate &meta, const char quote='\\')
Quote any meta-characters in given string.
Definition: stringOpsTemplates.C:32
Foam::stringOps::findTrim
std::pair< size_t, size_t > findTrim(const std::string &s, size_t pos=0, size_t len=std::string::npos)
Find (first, last) non-space locations in string or sub-string.
Foam::OSstream
Generic output stream using a standard (STL) stream.
Definition: OSstream.H:54
size_type
graph_traits< Graph >::vertices_size_type size_type
Definition: SloanRenumber.C:76
dict
dictionary dict
Definition: searchingEngine.H:14
Foam::dictionary
A list of keyword definitions, which are a keyword followed by a number of values (eg,...
Definition: dictionary.H:123
Foam::stringOps::splitAny
Foam::SubStrings< StringType > splitAny(const StringType &str, const std::string &delim)
Split string into sub-strings using any characters in delimiter.
Definition: stringOpsTemplates.C:170
scalar.H
Foam::stringOps::trimRight
string trimRight(const std::string &s)
Return string trimmed of trailing whitespace.
Definition: stringOps.C:972
os
OBJstream os(runTime.globalPath()/outputName)
Foam
Namespace for OpenFOAM.
Definition: atmBoundaryLayer.C:33
Foam::indent
Ostream & indent(Ostream &os)
Indent stream.
Definition: Ostream.H:339
Foam::HashTable
A HashTable similar to std::unordered_map.
Definition: HashTable.H:105
Foam::stringOps::inplaceLower
void inplaceLower(std::string &s)
Inplace transform string with std::tolower on each character.
Definition: stringOps.C:1194
Foam::stringOps::splitFixed
Foam::SubStrings< StringType > splitFixed(const StringType &str, const std::string::size_type width, const std::string::size_type start=0)
Split string into sub-strings using a fixed field width.
Definition: stringOpsTemplates.C:211
Foam::stringOps::inplaceTrimLeft
void inplaceTrimLeft(std::string &s)
Trim leading whitespace inplace.
Definition: stringOps.C:952
Foam::stringOps::match
bool match(const UList< wordRe > &patterns, const std::string &text)
Return true if text matches one of the regular expressions.
Definition: stringOps.H:76
SubStrings.H
Foam::wordRes::matcher
Functor wrapper for matching against a List of wordRe.
Definition: wordRes.H:83
Foam::stringOps::inplaceRemoveSpace
void inplaceRemoveSpace(std::string &s)
Eliminate whitespace inplace.
Definition: stringOps.C:1074
Foam::List
A 1D array of objects of type <T>, where the size of the vector is known and used for subscript bound...
Definition: BitOps.H:63
Foam::UList
A 1D vector of objects of type <T>, where the size of the vector is known and can be used for subscri...
Definition: HashTable.H:103
dictionary.H
Foam::wordRes
A List of wordRe with additional matching capabilities.
Definition: wordRes.H:51
Foam::constant::universal::c
const dimensionedScalar c
Speed of light in a vacuum.
Foam::stringOps::count
std::string::size_type count(const std::string &s, const char c)
Count the number of occurrences of the specified character.
Definition: stringOps.C:697
word.H
Foam::Tuple2
A 2-tuple for storing two objects of dissimilar types. The container is similar in purpose to std::pa...
Definition: stringOps.H:60
Foam::stringOps::upper
string upper(const std::string &s)
Return string copy transformed with std::toupper on each character.
Definition: stringOps.C:1200
Foam::stringOps::validate
StringType validate(const std::string &str, const UnaryPredicate &accept, const bool invert=false)
Return a copy of the input string with validated characters.
Definition: stringOpsTemplates.C:71
Foam::stringOps::removeComments
string removeComments(const std::string &s)
Return string with C/C++ comments removed.
Definition: stringOps.C:1080
Foam::stringOps::inplaceUpper
void inplaceUpper(std::string &s)
Inplace transform string with std::toupper on each character.
Definition: stringOps.C:1210
Foam::stringOps::expand
string expand(const std::string &s, const HashTable< string > &mapping, const char sigil='$')
Definition: stringOps.C:718
args
Foam::argList args(argc, argv)
Foam::stringOps::splitFunctionArgs
label splitFunctionArgs(const std::string &str, wordRes &args, List< Tuple2< word, string >> &namedArgs)
Split out arguments (named or unnamed) from an input string.
Definition: stringOpsSplit.C:57
Foam::pos
dimensionedScalar pos(const dimensionedScalar &ds)
Definition: dimensionedScalar.C:177