Notes from Looking Glass

08/18/2014 New functions for working with strings

Implemented in version 8.3.6.1977.

We have expanded the set of functions for working with strings. We did this in order to give you more advanced tools for parsing string data. New functions will be convenient and useful in technological tasks of text analysis. In tasks related to the parsing of text that contains data in a formatted form. This may be the analysis of some files received from the equipment, or, for example, the analysis of a technological log.

All the actions that the new functions perform, you could perform before. With the help of more or less complex algorithms written in an embedded language. Therefore, new functions do not give you any fundamentally new opportunities. However, they allow you to reduce the amount of code, make the code simpler and more understandable. In addition, they allow you to speed up the execution of actions. Because the functions implemented in the platform work, of course, faster than a similar algorithm written in the built-in language.

Format function StrTemplate()

This function substitutes parameters into a string. The need for such a conversion often arises, for example, when displaying warning messages. The syntax for this function is as follows:

StrTemplate(<Шаблон>, <Значение1-Значение10>)

<Шаблон>is the string in which to substitute the parameter representations.

<Значение1> , ... <Значение10>- these are the parameters (maximum - ten), the representations of which must be substituted into the string.

To specify a specific place in the template to which you want to perform the substitution, you need to use markers of the form %1, ... %10. The number of markers involved in the template and the number of parameters containing values ​​must match.

For example, the result of executing such an operator:

there will be a line:

Data error on line 2 (requires Date type)

String Function StrCompare()

This function compares two strings case insensitively. For example, like this:

You could perform the same action before using the object Comparing Values:

However, using the new function looks simpler. And besides this, a function, unlike an object Comparing Values, works in thin client, and in the web client.

String Functions StrBeginsC(), StrEndsTo()

These functions determine whether a string starts with a specified substring, or whether a string ends with a specified substring. The algorithm of these functions is not difficult to implement in a built-in language, but their presence allows you to write cleaner and more understandable code. And they work faster.

For example, it is convenient to use them in the operator If a:

Functions for working with strings StrSplit(), StrJoin()

These functions split the string into parts according to the specified delimiter. Or vice versa, they combine several lines into one, inserting the selected separator between them. They are convenient for creating or analyzing logs, a technological log. For example, you can easily disassemble a technological log entry into parts suitable for further analysis:

Function of working with strings StrFind()

Instead of the old function Find() we have implemented new feature, which has additional features:

  • Search in different directions (from the beginning, from the end);
  • Search from the specified position;
  • Search for an occurrence with the specified number (second, third, etc.).

In fact, it duplicates the capabilities of the old function. This is done in order to maintain compatibility with modules compiled in older versions. old function Find() recommended not to be used again.

Below is an example using the new search capabilities. Searching backwards is useful when you need the last piece of a formalized string, such as the full name of a file in a URL. And searching from a specified position helps in cases where you need to search in a known fragment, and not in the entire string.

The String type is found in all programming languages. It is primitive, and in 1C there are many functions for working with it. In this article, we will take a closer look at various ways work with string types in 1C 8.3 and 8.2 with examples.

Line

In order to convert a variable of any type to a string, there is the "String ()" function of the same name. The input parameter will be the variable itself, the string representation of which is to be obtained.

String(False) // returns "No"
String(12345) // returns "12 345"
String(CurrentDate()) //"21.07.2017 11:55:36"

It is possible to convert to a string not only primitive types, but also others, for example, elements of directories and documents.

Abbreviated LP, Abbreviated L, Abbreviated P

As input parameters of these functions is a string type variable. The functions remove insignificant characters (spaces, carriage returns, etc.): from the left and right sides, only from the left side, and only from the right, respectively.

abbrl("Spaces on both sides will be removed") // "Spaces on both sides will be removed"
abbr("Spaces on both sides will be removed") // "Spaces on the left will be removed"
abbr(" Spaces on both sides will be removed ") // "Spaces on the right will be removed"

Leo, Right, Middle

These functions allow you to cut off part of a string. The Lion() function will return the part of the string on its left side of the specified length. The "Right()" function is similar, but cropping is done on the right. The "Wed()" function allows you to specify the character number from which the string will be selected and its length.

Lion("String variable", 4) // returns "Stro"
Right("String variable", 7) // returns "variable"
avg("String variable", 2, 5)// returns "troco"

StrLength

The function determines the number of characters that are contained in a string variable.

StrLength("Word") // the result of execution will be the number 5

Find

The function makes it possible to search for a part of a string in a string variable. The return value will be a number that indicates the position of the beginning of the found string. If no matches are found, zero is returned.

Note that the search is case sensitive. If there is more than one occurrence of the search substring in the original string, the function will return the beginning of the first occurrence.

Find("one, two, one, two, three", "two") // the function will return the number 6

Empty line

Using this function allows you to determine if a string is empty. Insignificant characters, such as space, carriage return, and others are not taken into account.

EmptyString("Vasily Ivanovich Pupkin") // the function will return False
EmptyString(" ") // the function will return True

VReg, NReg, TReg

These functions are very useful when comparing and converting string variables. "Vreg()" will return the original string in uppercase, "HReg()" in lowercase, and "TReg()" will format it so that the first character of each individual word is capitalized, and all subsequent characters are lowercase.

VReg("GENERAL DIRECTOR") // return value - "GENERAL DIRECTOR"
HReg("GENERAL DIRECTOR") // return value - "CEO"
TReg("GENERAL DIRECTOR") // return value - "General Director"

StrReplace

This function is analogous to the replacement in text editors. It allows you to substitute one character or set of characters for another in string variables.

StrReplace("red, white, yellow", ",", ";") // returns "red; white; yellow"

StrNumberRows

The function allows you to determine the number of lines separated by a carriage return in a text variable.

The loop in the example below will go through three circles because the StrNumberRows function will return the value 3:

For ind \u003d 1 by StrNumber of Lines ("Line1" + Symbols.PS + "String2" + Symbols.PS + "Line3") Loop
<тело цикла>
EndCycle;

StrGetString

This function works with multiline text in the same way as the previous one. It allows you to get a specific string from a text variable.

StrGetString("String1" + Symbols.PS + "String2" + Symbols.PS + "String3", 2) // returns "Line2"

StrNumberOccurrences

The function counts the number of occurrences of a character or substring in the searched string.

StrNumberInstallations("a;b;c;d; ", ";") // the function will return the number 4

Symbol and SymbolCode

These functions allow you to get a character by its Unicode code, as well as determine this code by the character itself.

SymbolCode("A") // the function will return the number 1 040
SymbolCode(1040) // the function will return "A"

Frequent tasks when working with strings

String Concatenation

To concatenate multiple strings (concatenate) just use the addition operator.

"Line 1" + "Line 2" //the result of adding two lines will be "Line 1 Line 2"

Type conversion

In order to convert a type to a string, for example, a reference to a dictionary element, a number, and so on, it is enough to use the "String ()" function. Functions like "ShortLP()" will also convert variables to a string, but immediately with cutting off insignificant characters.

String(1000) // will return "1000"

Please note that when converting a number to a string, the program automatically added a space separating the thousand. In order to avoid this, you can use the following structures:

StrReplace(String(1000),Characters.NPP,"") // returns "1000"

String(Format(1000,"CH=")) // will return "1000"

Quotes in a string

Quite often you will have to deal with the need to put quotes in a string variable. It can be either a request text written in the configurator, or just a variable. To solve this problem, you just need to set two quote characters.

Header = String("Horns and Hooves LLC is us!") // returns "Roga and Hooves LLC is us!"

Multiline, line break

In order to create a multiline text, it is enough to add line break characters (Symbols.PS) to it.

MultilineText = "First Line" + Characters.PS + "Second Line"

How to remove spaces

In order to remove spaces on the right or left, you can use the function "Stretch()" (as well as "Scrpt()" and "ScreenP()"):

StringWithoutSpaces = ShortLP(" Many letters ") // the function will return the value "Many letters"

If, after converting a number to a string, you need to remove non-breaking spaces, use the following construction:

StringWithoutSpaces = StrReplace(String(99999),Characters.NPP,"") // returns "99999"

Also, programmers often use the following construction, which allows you to remove or replace all spaces of a text variable with another character:

StringWithoutSpaces = StrReplace(" hello", " " ,"") // returns "hello"

Comparing strings to each other

You can compare terms with the usual equal sign. The comparison is case sensitive.

"hello" = "hello" // will return false
"Hello" = "Hello" // will return True
"Hello" = "Goodbye" // will return False

There are few mechanisms for working with strings in 1C queries. First, strings can be added. Secondly, a substring can be taken from a string. Thirdly, strings can be compared, including by pattern. That's about all you can do with strings.

String addition

The "+" operator is used to add strings in a query. You can only add strings of limited length.

SELECT "Name: " + Contractors.Name AS Column1 FROM Directory.Contractors AS Contractors WHERE Contractors.Reference = &Reference

Substring function

SUBSTRING(<Строка>, <НачальнаяПозиция>, <Длина>)

An analogue of the function Environment() from object model. The Substring() function can be applied to string type data and allows you to select a fragment <Строки> , starting with a number character <НачальнаяПозиция> (characters in a string are numbered from 1) and length <Длина> characters. The result of the function evaluation has a string type of variable length, and the length will be considered unlimited if <Строка> has unlimited length and parameter <Длина> is not a constant or greater than 1024.

If the string length is less than specified in the second parameter, then the function will return an empty string.

Attention! Using the SUBSTRING() function to convert strings of unlimited length to strings of limited length is not recommended. Instead, it is better to use the cast operator EXPRESS().

Function Similar

If we need to make sure that the string attribute meets certain criteria, we compare it:

SELECT Counterparties.Name AS Column1 FROM Directory.Counterparties AS Counterparties WHERE Counterparties.Name = "Gazprom"

But what if a more subtle comparison is needed? Not just for equality or inequality, but for similarity to a certain pattern? That's exactly what the LIKE function was created for.

LIKE - An operator to check if a string is similar to a pattern. Analogue of LIKE in SQL.

The LIKE operator allows you to compare the value of the expression specified to the left of it with the template string specified to the right. The expression value must be of type string. If the value of the expression matches the template, the result of the operator will be TRUE, otherwise it will be FALSE.

The following characters in the template string are service characters and have a different meaning from the string character:

  • % (percentage): a sequence containing any number of arbitrary characters;
  • _ (underscore): one arbitrary character;
  • […] (one or more characters within square brackets): any single character listed inside square brackets. An enumeration can contain ranges, such as a-z, meaning any character within the range, including the ends of the range;
  • [^…] (in square brackets a negation sign followed by one or more characters): Any single character other than those listed following the negation sign.

Any other symbol means itself and does not carry any additional load. If it is necessary to write one of the listed characters as itself, then it must be preceded by<Спецсимвол>. Myself<Спецсимвол>(any suitable character) is defined in the same statement after keyword SPECIAL SYMBOL.

String is one of the primitive data types in 1C:Enterprise 8 systems. Variables with type line contain text.

Type Variable Values line are in double quotes. Multiple Variables of this type can be folded.

Per1 = "Word 1" ;
Per2 = "Word 2" ;
Per3 = Per1 + " " + Per2 ;

Eventually Per3 will matter " Word 1 Word 2″.

In addition, 1C:Enterprise 8 systems provide functions for working with strings. Consider the main ones:

EnterString(<Строка>, <Подсказка>, <Длина>, <Многострочность>) — the function is intended to display a dialog box in which the user can specify a value type variable Line. Parameter <Строка> is required and contains the name of the variable into which the entered string will be written. Parameter <Подсказка> optional is the title of the dialog box. Parameter <Длина> optional, indicates the maximum length of the input string. The default is zero, which means unlimited length. Parameter <Многострочность> optional. Specifies the input mode multiline text: True - enter multiline text with line separators; False - Enter a simple string.

A string can be entered and, knowing the character code in Unicode:

Symbol(<КодСимвола>) — The code is entered as a number.

Letter= Symbol(1103 ) ; // I

There is also inverse function, which allows you to find out the code of a character.

SymbolCode(<Строка>, <НомерСимвола>) — Returns the Unicode number of the specified character as a number.

Text case conversion functions:

VReg(<Строка>) - converts all characters of the string to uppercase.

HReg(<Строка>) - Converts all characters in a string to lower case.

TReg(<Строка>) - converts all characters of the string to title case. That is, the first letters in all words are converted to uppercase, and the remaining letters are converted to lowercase.

Functions for searching and replacing characters in a string:

Find(<Строка>, <ПодстрокаПоиска>) - finds the character number of the occurrence of the search substring. For example:

Find ("String" , "eye" ) ; // four

StrFind(<Строка>, <ПодстрокаПоиска>, <НаправлениеПоиска>, <НачальнаяПозиция>, <НомерВхождения>) — finds the character number of the occurrence of the search substring, the occurrence number is specified in the corresponding parameter. In this case, the search starts from the character, the number of which is specified in the parameter StartPosition. The search is possible from the beginning or from the end of the string. For example:

Number4 Entry= StrFind( "Defensiveness", "o" , Search Direction. First, 1 , 4 ) ; // 7

StrReplace(<Строка>, <ПодстрокаПоиска>, <ПодстрокаЗамены>) Finds all occurrences of the search substring in the source string and replaces it with the replacement substring.

StrReplace("String" , "eye" , "" ) ; // Page

Empty line(<Строка>) - checks the string for significant characters. If there are no significant characters, or no characters at all, then the value is returned True. Otherwise - Lie.

StrNumberOccurrences(<Строка>, <ПодстрокаПоиска>) – calculates the number of occurrences of the search substring in the source string.

StrNumberOccurrences ( "Study, study and study again", "to study" , "" ) ; // 3

StrTemplate(<Строка>, <ЗначениеПодстановки1>…<ЗначениеПодстановкиN> — substitutes the parameters into the string by number. The string must contain substitution markers of the form: "%1..%N". Numbering of markers starts from 1. If the parameter value Undefined, the empty string is substituted.

StrPattern ( "Option 1 = %1, Option 2 = %2", "1" , "2" ) ; // Parameter 1= 1, Parameter 2 = 2

String conversion functions:

A lion(<Строка>, <ЧислоСимволов>) returns the first characters of the string.

Right(<Строка>, <ЧислоСимволов>) - returns the last characters of the string.

Wednesday(<Строка>, <НачальныйНомер>, <ЧислоСимволов>) - returns a string of length<ЧислоСимволов>, starting with a character<НачальныйНомер>.

Abbr(<Строка>) cuts off insignificant characters to the left of the first significant character in line.

abbr(<Строка>) - cuts off insignificant characters to the right of the last significant character in the string.

Abbrl(<Строка>) - cuts off non-significant characters to the left of the first significant character in the string and to the right of the last significant character in the string.

StrGetString(<Строка>, <НомерСтроки>) – gets the string of a multiline string by number.

Other features:

StrLength(<Строка>) - returns the number of characters in a string.

StrNumber of Lines(<Строка>) - returns the number of rows in a multiline string. A line is considered new if it is separated from the previous line by a newline character.

StrCompare(<Строка1>, <Строка2> ) - compares two strings case insensitively. The function works like an object Comparing Values. Returns:

  • 1 - if the first line is greater than the second
  • -1 - if the second line is greater than the first
  • 0 - if strings are equal

StrCompare("First row" , "Second row" ) ; // one