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-2025 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.cxx
35  stringOps.txx
36  stringOpsSplit.cxx
37  stringOpsSubstr.cxx
38 
39 \*---------------------------------------------------------------------------*/
40 
41 #ifndef Foam_stringOps_H
42 #define Foam_stringOps_H
43 
44 #include "scalar.H"
45 #include "dictionary.H"
46 #include "HashTable.H"
47 #include "SubStrings.H"
48 #include "stringOpsSort.H"
49 #include "stringOpsEvaluate.H"
50 #include "word.H"
51 #include "wordRes.H"
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  // Correctly handles nullptr.
70  std::string::size_type count(const char* s, const char c);
71 
72  //- Count the number of occurrences of the specified character
73  std::string::size_type count(const std::string& s, const char c);
74 
75  //- True if text matches one of the selector expressions
76  inline bool match(const UList<wordRe>& selectors, const std::string& text)
77  {
78  return wordRes::match(selectors, 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.
375  (
377  const std::string& str,
379  const char delim,
383  const bool keepEmpty = false
384  );
385 
386  //- Split string into sub-strings using delimiter string.
387  // Empty sub-strings are normally suppressed.
389  (
391  const std::string& str,
393  const std::string& delim,
397  const bool keepEmpty = false
398  );
399 
400  //- Split string into sub-strings using any characters in delimiter.
401  // Empty sub-strings are normally suppressed.
402  // Behaviour is ill-defined if delim is an empty string.
404  (
406  const std::string& str,
408  const std::string& delim,
411  );
412 
413  //- Split string into sub-strings using a fixed field width.
414  // Behaviour is ill-defined if width is zero.
416  (
418  const std::string& str,
420  const std::string::size_type width,
423  );
424 
425  //- Split string into sub-strings at whitespace (TAB, NL, VT, FF, CR, SPC)
426  // Empty sub-strings are suppressed.
428  (
430  const std::string& str,
433  );
434 
435  //- Output string with text wrapping.
436  // Always includes a trailing newline, unless the string itself is empty.
437  void writeWrapped
438  (
440  OSstream& os,
442  const std::string& str,
444  const std::string::size_type width,
446  const std::string::size_type indent = 0,
448  const bool escape = false
449  );
450 
451 } // End namespace stringOps
452 
453 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
454 
455 } // End namespace Foam
456 
457 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
458 
459 #ifdef NoRepository
460  #include "stringOps.txx"
461 #endif
462 
463 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
464 
465 #endif
466 
467 // ************************************************************************* //
Generic output stream using a standard (STL) stream.
Definition: OSstream.H:50
dictionary dict
Ostream & indent(Ostream &os)
Indent stream.
Definition: Ostream.H:491
Specialized string sorting.
Foam::SubStrings splitSpace(const std::string &str, std::string::size_type pos=0)
Split string into sub-strings at whitespace (TAB, NL, VT, FF, CR, SPC)
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:56
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 split(const std::string &str, const char delim, std::string::size_type pos=0, const bool keepEmpty=false)
Split string into sub-strings at the delimiter character.
std::string::size_type count(const char *s, const char c)
Count the number of occurrences of the specified character.
Foam::SubStrings splitAny(const std::string &str, const std::string &delim, std::string::size_type pos=0)
Split string into sub-strings using any characters in delimiter.
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.
void inplaceTrimRight(std::string &s)
Trim trailing whitespace inplace.
Sub-ranges of a string with a structure similar to std::match_results, but without the underlying reg...
Definition: SubStrings.H:45
bool match(const UList< wordRe > &selectors, const std::string &text)
True if text matches one of the selector expressions.
Definition: stringOps.H:79
string trimRight(const std::string &s)
Return string trimmed of trailing whitespace.
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)
string trimLeft(const std::string &s)
Return string trimmed of leading whitespace.
A class for handling words, derived from Foam::string.
Definition: word.H:63
StringType quotemeta(const StringType &str, const UnaryPredicate &meta, const char quote='\\')
Quote any meta-characters in given string.
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.
void inplaceRemoveSpace(std::string &s)
Eliminate whitespace inplace.
A HashTable similar to std::unordered_map.
Definition: HashTable.H:108
graph_traits< Graph >::vertices_size_type size_type
Definition: SloanRenumber.C:67
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
label splitFunctionArgs(const std::string &str, wordRes &args, List< Tuple2< word, string >> &namedArgs)
Split out arguments (named or unnamed) from an input string.
OBJstream os(runTime.globalPath()/outputName)
void inplaceRemoveComments(std::string &s)
Remove C/C++ comments inplace.
string upper(const std::string &s)
Return string copy transformed with std::toupper on each character.
labelList invert(const label len, const labelUList &map)
Create an inverse one-to-one mapping.
Definition: ListOps.C:28
void inplaceUpper(std::string &s)
Inplace transform string with std::toupper on each character.
static bool match(const UList< wordRe > &selectors, const std::string &text, bool literal=false)
Test for a match of any selectors against the text.
Definition: wordResI.H:47
void inplaceTrimLeft(std::string &s)
Trim leading whitespace inplace.
bool inplaceReplaceVar(std::string &s, const word &varName)
Replace environment variable contents with its name.
void inplaceTrim(std::string &s)
Trim leading and trailing whitespace inplace.
const dimensionedScalar c
Speed of light in a vacuum.
string lower(const std::string &s)
Return string copy transformed with std::tolower on each character.
Foam::SubStrings splitFixed(const std::string &str, const std::string::size_type width, std::string::size_type pos=0)
Split string into sub-strings using a fixed field width.
void inplaceLower(std::string &s)
Inplace transform string with std::tolower on each character.
String expression evaluation.
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...
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.
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)
string removeComments(const std::string &s)
Return string with C/C++ comments removed.
Namespace for OpenFOAM.