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-2020 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& s, 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* s, 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& s,
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& s,
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(const std::string& s, const bool allowEmpty = false);
250 
251 
252  //- Expand initial tags, tildes, and all occurrences of environment
253  //- variables
254  //
255  // The expansion behaviour is identical to
256  // stringOps::inplaceExpand
257  // (std::string&, const dictionary&, bool, bool, bool, char)
258  // except that there is no dictionary and the environment variables
259  // are always enabled.
260  //
261  // \par Expansion behaviour
262  // - alternatives = True
263  // - environment = True
264  // - allow empty = Given by parameter (default: False)
265  // - subDict = Not applicable
266  // .
267  void inplaceExpand(std::string& s, const bool allowEmpty = false);
268 
269 
270  //- Replace environment variable contents with its name.
271  // This is essentially the inverse operation for inplaceExpand
272  // for a single element.
273  // Return true if a replacement was successful.
274  bool inplaceReplaceVar(std::string& s, const word& varName);
275 
276 
277  //- Find (first, last) non-space locations in string or sub-string.
278  // This may change to std::string_view in the future.
279  std::pair<size_t, size_t>
280  findTrim
281  (
282  const std::string& s,
283  size_t pos = 0,
284  size_t len = std::string::npos
285  );
286 
287  //- Return string trimmed of leading whitespace
288  string trimLeft(const std::string& s);
289 
290  //- Trim leading whitespace inplace
291  void inplaceTrimLeft(std::string& s);
292 
293  //- Return string trimmed of trailing whitespace
294  string trimRight(const std::string& s);
295 
296  //- Trim trailing whitespace inplace
297  void inplaceTrimRight(std::string& s);
298 
299  //- Return string trimmed of leading and trailing whitespace
300  string trim(const std::string& s);
301 
302  //- Trim leading and trailing whitespace inplace
303  void inplaceTrim(std::string& s);
304 
305  //- Eliminate whitespace inplace
306  void inplaceRemoveSpace(std::string& s);
307 
308 
309  //- Return string with C/C++ comments removed
310  string removeComments(const std::string& s);
311 
312  //- Remove C/C++ comments inplace
313  void inplaceRemoveComments(std::string& s);
314 
315 
316  //- Return string copy transformed with std::tolower on each character
317  string lower(const std::string& s);
318 
319  //- Inplace transform string with std::tolower on each character
320  void inplaceLower(std::string& s);
321 
322  //- Return string copy transformed with std::toupper on each character
323  string upper(const std::string& s);
324 
325  //- Inplace transform string with std::toupper on each character
326  void inplaceUpper(std::string& s);
327 
328 
329  //- Split string into sub-strings at the delimiter character.
330  // Empty sub-strings are normally suppressed.
331  // Behaviour is ill-defined if delim is a NUL character.
332  template<class StringType>
334  (
335  const StringType& str,
336  const char delim,
337  const bool keepEmpty = false
338  );
339 
340  //- Split string into sub-strings using delimiter string.
341  // Empty sub-strings are normally suppressed.
342  template<class StringType>
344  (
345  const StringType& str,
346  const std::string& delim,
347  const bool keepEmpty = false
348  );
349 
350  //- Split string into sub-strings using any characters in delimiter.
351  // Empty sub-strings are normally suppressed.
352  // Behaviour is ill-defined if delim is an empty string.
353  template<class StringType>
355  (
356  const StringType& str,
357  const std::string& delim
358  );
359 
360  //- Split string into sub-strings using a fixed field width.
361  // Behaviour is ill-defined if width is zero.
362  // \param str the string to be split
363  // \param width the fixed field width for each sub-string
364  // \param start the optional offset of where to start the splitting.
365  // Any text prior to start is ignored in the operation.
366  template<class StringType>
368  (
369  const StringType& str,
370  const std::string::size_type width,
371  const std::string::size_type start = 0
372  );
373 
374  //- Split string into sub-strings at whitespace (TAB, NL, VT, FF, CR, SPC)
375  // Empty sub-strings are suppressed.
376  template<class StringType>
378  (
379  const StringType& str
380  );
381 
382  //- Output string with text wrapping.
383  // Always includes a trailing newline, unless the string itself is empty.
384  //
385  // \param os the output stream
386  // \param str the text to be output
387  // \param width the max-width before wrapping
388  // \param indent indentation for continued lines
389  // \param escape escape any backslashes on output
390  void writeWrapped
391  (
392  OSstream& os,
393  const std::string& str,
394  const std::string::size_type width,
395  const std::string::size_type indent = 0,
396  const bool escape = false
397  );
398 
399 } // End namespace stringOps
400 
401 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
402 
403 } // End namespace Foam
404 
405 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
406 
407 #ifdef NoRepository
408  #include "stringOpsTemplates.C"
409 #endif
410 
411 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
412 
413 #endif
414 
415 // ************************************************************************* //
stringOpsEvaluate.H
String expression evaluation.
wordRes.H
Foam::stringOps::inplaceTrimRight
void inplaceTrimRight(std::string &s)
Trim trailing whitespace inplace.
Definition: stringOps.C:994
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:1219
stringOpsSort.H
Specialized string sorting.
Foam::stringOps::inplaceTrim
void inplaceTrim(std::string &s)
Trim leading and trailing whitespace inplace.
Definition: stringOps.C:1069
Foam::stringOps::inplaceReplaceVar
bool inplaceReplaceVar(std::string &s, const word &varName)
Replace environment variable contents with its name.
Definition: stringOps.C:908
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
Foam::stringOps::trim
string trim(const std::string &s)
Return string trimmed of leading and trailing whitespace.
Definition: stringOps.C:1048
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:180
Foam::stringOps::trimLeft
string trimLeft(const std::string &s)
Return string trimmed of leading whitespace.
Definition: stringOps.C:932
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:1090
Foam::stringOps::expand
string expand(const std::string &s, const HashTable< string, word, string::hash > &mapping, const char sigil='$')
Definition: stringOps.C:720
Foam::stringOps::lower
string lower(const std::string &s)
Return string copy transformed with std::tolower on each character.
Definition: stringOps.C:1186
Foam::stringOps::inplaceExpand
void inplaceExpand(std::string &s, const HashTable< string, word, string::hash > &mapping, const char sigil='$')
Definition: stringOps.C:733
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: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:974
Foam
Namespace for OpenFOAM.
Definition: atmBoundaryLayer.C:33
Foam::indent
Ostream & indent(Ostream &os)
Indent stream.
Definition: Ostream.H:320
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:1196
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:954
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::inplaceRemoveSpace
void inplaceRemoveSpace(std::string &s)
Eliminate whitespace inplace.
Definition: stringOps.C:1076
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.
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:699
word.H
Foam::stringOps::upper
string upper(const std::string &s)
Return string copy transformed with std::toupper on each character.
Definition: stringOps.C:1202
Foam::stringOps::removeComments
string removeComments(const std::string &s)
Return string with C/C++ comments removed.
Definition: stringOps.C:1082
Foam::stringOps::inplaceUpper
void inplaceUpper(std::string &s)
Inplace transform string with std::toupper on each character.
Definition: stringOps.C:1212
Foam::pos
dimensionedScalar pos(const dimensionedScalar &ds)
Definition: dimensionedScalar.C:177