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