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-2019 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 
61 /*---------------------------------------------------------------------------*\
62  Namespace stringOps Declaration
63 \*---------------------------------------------------------------------------*/
64 
65 namespace stringOps
66 {
67  //- Count the number of occurrences of the specified character
68  std::string::size_type count(const std::string& str, const char c);
69 
70  //- Count the number of occurrences of the specified character
71  // Correctly handles nullptr.
72  std::string::size_type count(const char* str, const char c);
73 
74  //- Return true if text matches one of the regular expressions.
75  inline bool match(const UList<wordRe>& patterns, const std::string& text)
76  {
77  return wordRes::matcher(patterns)(text);
78  }
79 
80  //- Expand occurrences of variables according to the mapping
81  //- and return the expanded string.
82  //
83  // \sa stringOps::inplaceExpand() for details
84  string expand
85  (
86  const std::string& str,
88  const char sigil = '$'
89  );
90 
91  //- Inplace expand occurrences of variables according to the mapping.
92  //- Does \b not use environment values.
93  //
94  // Expansion includes:
95  // -# Variables
96  // - \c $VAR
97  // - \c ${VAR}
98  //
99  // -# Default and alternative values as per the POSIX shell:
100  // - \c ${parameter:-defValue}
101  // If parameter is unset or null, the \c defValue is substituted.
102  // Otherwise, the value of parameter is substituted.
103  // - \c ${parameter:+altValue}
104  // If parameter is unset or null, nothing is substituted.
105  // Otherwise the \c altValue is substituted.
106  // .
107  //
108  // General behaviour:
109  // - Unknown entries are removed silently.
110  // - Malformed entries (eg, brace mismatch, sigil followed by unknown
111  // characters) are left as is.
112  //
113  // \param[in,out] s The string to modify inplace.
114  // \param mapping The lookup table
115  // \param sigil The leading sigil. Can be changed to avoid conflict
116  // with other string expansions. (default: '$')
117  //
118  // \par Expansion behaviour
119  // - alternatives = True
120  // - environment = False
121  // - allow empty = True
122  // - subDict = Not applicable
123  // .
124  //
125  // \note Currently only used by Foam::dynamicCode.
126  void inplaceExpand
127  (
128  std::string& s,
130  const char sigil = '$'
131  );
132 
133 
134  //- Inplace expand occurrences of variables according to the dictionary
135  //- and (optionally) environment variables.
136  //
137  // Expansion includes:
138  // -# Dictionary variables and (optionally) environment variables
139  // - \c $VAR
140  // - \c ${VAR}
141  // - \c ${VAR:-defValue}
142  // - \c ${VAR:+altValue}
143  // -# Mathematical evaluation using stringOps::evaluate
144  // - \c ${{EXPR}}
145  // -# Current directory
146  // - leading "./"
147  // : the current directory - Foam::cwd()
148  // -# Leading tag expansion for commonly used directories
149  // - <b> <etc>/ </b>
150  // : user/group/other OpenFOAM etc directory
151  // - <b> <etc:</b><em>[ugoa]+</em>)<b>>/ </b>
152  // : user/group/other etc with specified location mode
153  // - <b> <case>/ </b>
154  // : The \c $FOAM_CASE directory
155  // - <b> <constant>/ </b>
156  // : The \c $FOAM_CASE/constant directory
157  // - <b> <system>/ </b>
158  // : The \c $FOAM_CASE/system directory
159  // -# Tilde expansion
160  // - leading "~/" : home directory
161  // - leading "~user" : home directory for specified user
162  // -# Default and alternative values as per the POSIX shell:
163  // - \c ${parameter:-defValue}
164  // If parameter is unset or null, the \c defValue is substituted.
165  // Otherwise, the value of parameter is substituted.
166  // - \c ${parameter:+altValue}
167  // If parameter is unset or null, nothing is substituted.
168  // Otherwise the \c altValue is substituted.
169  // .
170  //
171  // General behaviour:
172  // - Malformed entries (eg, brace mismatch, sigil followed by unknown
173  // characters) are left as is.
174  // - Supports recursive variable expansions.
175  // For example, "${var${num}}" and "${{100 + ${var}}}"
176  //
177  // \param[in,out] s The string to modify inplace
178  // \param dict The dictionary context for the expansion
179  // \param allowEnv Allow use of environment values as fallback
180  // \param allowEmpty Allow empty expansions, or treat as Fatal
181  // \param allowSubDict Allow expansion of subDict entries as well as
182  // primitive entries (default: false)
183  // \param sigil The leading sigil. Can be changed to avoid conflict
184  // with other string expansions. (default: '$')
185  //
186  // \sa Foam::findEtcEntry(), Foam::findEtcEntries(), stringOps::evaluate()
187  //
188  // \par Expansion behaviour
189  // - alternatives = True
190  // - environment = Given by parameter
191  // - allow empty = Given by parameter
192  // - subDict = Given by parameter (default: False)
193  // .
194  //
195  // \note This function has too many parameters and should generally
196  // be avoided in user coding.
197  void inplaceExpand
198  (
199  std::string& s,
200  const dictionary& dict,
201  const bool allowEnv,
202  const bool allowEmpty,
203  const bool allowSubDict = false,
204  const char sigil = '$'
205  );
206 
207 
208  //- Expand occurrences of dictionary or environment variables.
209  //
210  // Empty expansions are allowed.
211  // Serialization of subDict entries is permitted.
212  //
213  // \sa stringOps::inplaceExpand(std::string&, const dictionary&, char)
214  string expand
215  (
216  const std::string& str,
217  const dictionary& dict,
218  const char sigil = '$'
219  );
220 
221  //- Inplace expand occurrences of dictionary or environment variables.
222  //
223  // Empty expansions are allowed.
224  // Serialization of subDict entries is permitted.
225  //
226  // \sa
227  // stringOps::inplaceExpand
228  // (std::string&, const dictionary&, bool, bool, bool, char)
229  //
230  // \par Expansion behaviour
231  // - alternatives = True
232  // - environment = True
233  // - allow empty = True
234  // - subDict = True
235  // .
236  void inplaceExpand
237  (
238  std::string& s,
239  const dictionary& dict,
240  const char sigil = '$'
241  );
242 
243 
244  //- Expand initial tags, tildes, and all occurrences of environment
245  //- variables.
246  //
247  // \sa
248  // stringOps::inplaceExpand(std::string&, bool);
249  string expand
250  (
251  const std::string& str,
252  const bool allowEmpty = false
253  );
254 
255 
256  //- Expand initial tags, tildes, and all occurrences of environment
257  //- variables
258  //
259  // The expansion behaviour is identical to
260  // stringOps::inplaceExpand
261  // (std::string&, const dictionary&, bool, bool, bool, char)
262  // except that there is no dictionary and the environment variables
263  // are always enabled.
264  //
265  // \par Expansion behaviour
266  // - alternatives = True
267  // - environment = True
268  // - allow empty = Given by parameter (default: False)
269  // - subDict = Not applicable
270  // .
271  void inplaceExpand
272  (
273  std::string& s,
274  const bool allowEmpty = false
275  );
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 
285  //- Find (first, last) non-space locations in string or sub-string.
286  // This may change to std::string_view in the future.
287  std::pair<size_t, size_t>
288  findTrim
289  (
290  const std::string& s,
291  size_t pos = 0,
292  size_t len = std::string::npos
293  );
294 
295  //- Return string trimmed of leading whitespace
296  string trimLeft(const std::string& s);
297 
298  //- Trim leading whitespace inplace
299  void inplaceTrimLeft(std::string& s);
300 
301  //- Return string trimmed of trailing whitespace
302  string trimRight(const std::string& s);
303 
304  //- Trim trailing whitespace inplace
305  void inplaceTrimRight(std::string& s);
306 
307  //- Return string trimmed of leading and trailing whitespace
308  string trim(const std::string& str);
309 
310  //- Trim leading and trailing whitespace inplace
311  void inplaceTrim(std::string& s);
312 
313 
314  //- Return string with C/C++ comments removed
315  string removeComments(const std::string& str);
316 
317  //- Remove C/C++ comments inplace
318  void inplaceRemoveComments(std::string& s);
319 
320 
321  //- Return string transformed with std::tolower on each character
322  string lower(const std::string& str);
323 
324  //- Inplace transform string with std::tolower on each character
325  void inplaceLower(std::string& s);
326 
327  //- Return string transformed with std::toupper on each character
328  string upper(const std::string& str);
329 
330  //- Inplace transform string with std::toupper on each character
331  void inplaceUpper(std::string& s);
332 
333 
334  //- Split string into sub-strings at the delimiter character.
335  // Empty sub-strings are normally suppressed.
336  // Behaviour is ill-defined if delim is a NUL character.
337  template<class StringType>
339  (
340  const StringType& str,
341  const char delim,
342  const bool keepEmpty = false
343  );
344 
345  //- Split string into sub-strings using delimiter string.
346  // Empty sub-strings are normally suppressed.
347  template<class StringType>
349  (
350  const StringType& str,
351  const std::string& delim,
352  const bool keepEmpty = false
353  );
354 
355  //- Split string into sub-strings using any characters in delimiter.
356  // Empty sub-strings are normally suppressed.
357  // Behaviour is ill-defined if delim is an empty string.
358  template<class StringType>
360  (
361  const StringType& str,
362  const std::string& delim
363  );
364 
365  //- Split string into sub-strings using a fixed field width.
366  // Behaviour is ill-defined if width is zero.
367  // \param str the string to be split
368  // \param width the fixed field width for each sub-string
369  // \param start the optional offset of where to start the splitting.
370  // Any text prior to start is ignored in the operation.
371  template<class StringType>
373  (
374  const StringType& str,
375  const std::string::size_type width,
376  const std::string::size_type start = 0
377  );
378 
379  //- Split string into sub-strings at whitespace (TAB, NL, VT, FF, CR, SPC)
380  // Empty sub-strings are suppressed.
381  template<class StringType>
383  (
384  const StringType& str
385  );
386 
387  //- Output string with text wrapping.
388  // Always includes a trailing newline, unless the string itself is empty.
389  //
390  // \param os the output stream
391  // \param str the text to be output
392  // \param width the max-width before wrapping
393  // \param indent indentation for continued lines
394  // \param escape escape any backslashes on output
395  void writeWrapped
396  (
397  OSstream& os,
398  const std::string& str,
399  const std::string::size_type width,
400  const std::string::size_type indent = 0,
401  const bool escape = false
402  );
403 
404 } // End namespace stringOps
405 
406 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
407 
408 } // End namespace Foam
409 
410 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
411 
412 #ifdef NoRepository
413  #include "stringOpsTemplates.C"
414 #endif
415 
416 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
417 
418 #endif
419 
420 // ************************************************************************* //
stringOpsEvaluate.H
String expression evaluation.
wordRes.H
Foam::stringOps::inplaceTrimRight
void inplaceTrimRight(std::string &s)
Trim trailing whitespace inplace.
Definition: stringOps.C:1013
Foam::word
A class for handling words, derived from Foam::string.
Definition: word.H:62
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:1240
stringOpsSort.H
Specialized string sorting.
Foam::stringOps::inplaceTrim
void inplaceTrim(std::string &s)
Trim leading and trailing whitespace inplace.
Definition: stringOps.C:1088
Foam::stringOps::inplaceReplaceVar
bool inplaceReplaceVar(std::string &s, const word &varName)
Replace environment variable contents with its name.
Definition: stringOps.C:927
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:32
stringOpsTemplates.C
string.H
Foam::stringOps::lower
string lower(const std::string &str)
Return string transformed with std::tolower on each character.
Definition: stringOps.C:1199
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:180
Foam::stringOps::trimLeft
string trimLeft(const std::string &s)
Return string trimmed of leading whitespace.
Definition: stringOps.C:951
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:1103
Foam::stringOps::count
std::string::size_type count(const std::string &str, const char c)
Count the number of occurrences of the specified character.
Definition: stringOps.C:698
Foam::stringOps::inplaceExpand
void inplaceExpand(std::string &s, const HashTable< string, word, string::hash > &mapping, const char sigil='$')
Definition: stringOps.C:752
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::stringOps::upper
string upper(const std::string &str)
Return string transformed with std::toupper on each character.
Definition: stringOps.C:1219
Foam::OSstream
Generic output stream.
Definition: OSstream.H:54
size_type
graph_traits< Graph >::vertices_size_type size_type
Definition: SloanRenumber.C:75
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:121
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:104
scalar.H
Foam::stringOps::trimRight
string trimRight(const std::string &s)
Return string trimmed of trailing whitespace.
Definition: stringOps.C:993
Foam
Namespace for OpenFOAM.
Definition: atmBoundaryLayer.C:33
Foam::stringOps::removeComments
string removeComments(const std::string &str)
Return string with C/C++ comments removed.
Definition: stringOps.C:1095
Foam::indent
Ostream & indent(Ostream &os)
Indent stream.
Definition: Ostream.H:307
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:1207
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:145
Foam::stringOps::inplaceTrimLeft
void inplaceTrimLeft(std::string &s)
Trim leading whitespace inplace.
Definition: stringOps.C:973
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:75
SubStrings.H
Foam::wordRes::matcher
Functor wrapper for matching against a List of wordRe.
Definition: wordRes.H:82
Foam::stringOps::expand
string expand(const std::string &str, const HashTable< string, word, string::hash > &mapping, const char sigil='$')
Definition: stringOps.C:739
Foam::start
label ListType::const_reference const label start
Definition: ListOps.H:408
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::constant::universal::c
const dimensionedScalar c
Speed of light in a vacuum.
word.H
Foam::stringOps::inplaceUpper
void inplaceUpper(std::string &s)
Inplace transform string with std::toupper on each character.
Definition: stringOps.C:1227
Foam::stringOps::trim
string trim(const std::string &str)
Return string trimmed of leading and trailing whitespace.
Definition: stringOps.C:1067
Foam::pos
dimensionedScalar pos(const dimensionedScalar &ds)
Definition: dimensionedScalar.C:177