Functions in 1C with strings. New functions for working with strings. Functions for working with strings StrDivide(), StrConnect()

As an example of how the functions for working with 1C strings work, we would like to create an automatic text analysis. We will take the text from the file. The result of the analysis is displayed in any form to the user.

We need to create an external handler that will allow us to select a text file and run the analyzer.

Text analysis 1C - form and buttons

So, let's create external processing: Configurator/File/New/External processing.

Adding a form. We need to place a selection field on the form text file and an analysis button.

Text analysis 1C - thick client

Let's place a regular text field on the form. The length of the line is unlimited, because the path to the file (directory names) can be significant.

So that the user does not have to enter the file name, but can select it, we will enable a selection button in the field.

We will change the field name to “FileName”, the name of the associated form attribute will change to the same automatically.

As a button we will use the “Run” button automatically added by the platform (and it already has a handler connected - convenient).

Text analysis 1C - thin client

In the thin client, we will independently create the “FileName” form attribute. Let's drag the props onto the form. In the properties of the form element we will also enable the select button.

As a button, we will create the “Run” command, assign processing to it and drag it onto the form.

Text analysis 1C - programming

The first thing we need to do is process the click of the selection button - show a file selection dialog when clicked.

Let's go to the properties of our text field on the form (in the thick client - with the left mouse button directly on the field, in the thin client - on the name of the field in the list), and specify the event handler for the "Start of Selection" event.

Inside the handler function that 1C will create when assigned, we will write some simple code:

Now we have a file name. We need to “get” its contents and call the text analysis.

We already have a handler for the Run button. In the thick client, the button and its handler were created automatically by the 1C configurator. In the thin client we added it manually.

Let's add code to the handler that reads the file into a string:

Regarding the file encoding. If you create a TextReading() object without a parameter indicating the encoding, 1C will try to independently determine the encoding (by the signature Byte Order Mark - BOM, or will consider its ANSI encoding).

You can specify the desired encoding directly, for example like this:
File = New ReadText(FileName, "UTF-8"); //substitute the desired encoding name

So, as a result we got:

  • Text string read from file in variable "Text"
  • A procedure in which we will analyze the resulting string from a variable called “TextAnalysis()”, using the 1C string functions

PART 1. METHODS (26).

1.1. Basic methods (10). Independent, built on their own simple algorithms.

Page_Add() (right-left addition with specified characters).

Page_Inverse () (inversion - characters from right to left).

Page_Codes() (character codes through ”,” and an array with codes)

Page_Characters() (a string of codes separated by ”,” or from an array with codes)

Page_ReplaceSymbols() (replacing some characters with others).

String_FromArray() (string from an array of fragments separated by a separator)

Page_FindIn() (search for a substring (including on the right) with a specified occurrence number).

Page_FindGr() (Search for a group of characters included in the specified character set)

Page_FindNumber() (Search for a number, including on the right with specified number occurrences)

Page_Interpret() (into an array, according to the established syntax)

1.2. Derivative methods (12). Actually, this is the use of four generalized algorithm methods (see Part 2)

Page_Number() (from the beginning and from the end of the line, do not be “afraid” of non-numeric characters.

Page_Find() (search for a substring (including case-insensitive and to the right) with a specified occurrence number).

Page_Replace() (search (including case-insensitive and right-handed), and replace delimiter substrings).

String_Piece() (a piece of string between the specified occurrences of the delimiter (left or right)).

Page_ReplacePiece() (replaces “chunk” in the source string with the specified string).

Page_ВArray() (between the specified occurrences of the separator (including those on the right and without case).

Page_TransferBySyllables() (split into substrings “Hardly”, with a hyphen).

Page_TransferByWords() (split into substrings “Softly”)

Page_Cut() (“Cut” into substrings of specified lengths)

Str_Shorten() (replace the left group of "abbreviated" characters with a "replacement string"

Page_Abbreviation() (replace the right group of “reduced” characters with a “replacement string”

Str_ShortenS() (replace in the middle of the group of “shortened” characters with a “replacement string”

Page_Extend (expansion to a specified length by increasing the number of specified characters)

1.3. Detailed methods (3). "Dissecting" a line with transfer to a table with detailed information.

Page_vTableIn() (into the table according to the system of nested delimiters).

Page_vTableGr (to the table according to a multi-level filter).

Page_inTableNumbers (in a table with numbers and fragments between them).

PART 2. GENERALIZED METHODS-ALGORIMS (3).

Page_Occurrence() (methods “Find” and “Replace”).

Page_Fragments() (methods “Piece”,”ReplacePiece,”InArray”,”inTableIn”).

Page_Abcr() (methods "AbcrL", "AbcrP", "AbcrS", "Expand".

Page_Split() (methods “Move By Syllables,” “Move By Words,” “Cut”).

PART 3. UNIVERSAL FUNCTION.

This is a kind of conditional programming interface that allows

apply several methods to a string at once. Implemented as

functions with seven parameters ("Demo" is built on this function):

Page_(Methods, Submethods, Input, Param1, Param2, Length_Number_Position, Additional Output)

Options:

- “Methods” - several “combined” and (or) one “exclusive” method

(single-character codes or names, possible via ",")

- “Submethods” - several “combined” and (or) “exclusive” options

“exclusive” method (single-character codes or names);

- “Input” - String, or Array or Table of values;

- “Param1” - search string, substitutions, separators, filters;

- “Param2” - replacement string or characters;

- “Length_Number_Position” -Number, Numbers through a separator or an array with Numbers;

- “Additional Output” - Number or String or Array or Table of Values;

Names and/or one-character codes of submethods, as well as numbers in

(Length_Number_Position) can be in any case and separated

any of the following delimiters: ”, :;”.

PART 4. SOME EXAMPLES.

There areNumbersInLine=(Str_FindNumber(InLine)<>Undefined);

There are Numbers in the Line = (String_FindGr(Inline,"+0123456789")>0);

There is Latin = (Str_FindGr(InStr, Str_Interpret("lL"))>0);

There are Specified Signs = (Str_NfindGr(VxStr, "+to rogYu.0p9")>0);

IsNotPrinted=(Str_FindGr(InxStr, Line_Interpret("-l-L-r-R-P-Z-C"))>0);

PART 5. CONCLUSION.

Where possible, I made do with one pass along the line. The second pass is usually in fragments. I did not use the built-in function StrNumberOccurrences().

Built-in functions are used: Left(), Right(), Middle(), StrLength()

- (positioning and getting part of the line must be “fast”).

TO basic capabilities Programming languages ​​usually involve working with numbers and strings. Usually these features are hard-coded into the compiler code (or the “base” classes of the programming language are implemented).

In 1C, the ability to work with strings is programmed in the platform itself. Today we will look at the features of working with 1C strings in programs in the built-in 1C language.

Line value 1C

1. Let's start with the simplest. Creating a variable and assigning a constant string value to it looks like this in 1C:

Variable = "Hello, world!";

If you need to specify a quote character in a constant 1C string value, then you need to double it “”

Variable = "Hello, world"!;

2. Line break 1C can be specified in two ways at once. The first is using the symbol |

Variable = "Hello,
| world! ";

The second is using the Symbols system enumeration. It allows you to add both 1C line breaks and other non-printing characters, such as TAB.

Variable = "Hello" + Symbols.PS + "peace!";

3. Configurations in 1C can be developed not only for one language (Russian, English or another) - but simultaneously for several languages. In this case, the currently used language is selected at the bottom of the 1C window.

The list of languages ​​is located in the configuration window in the General/Languages ​​branch. Each language has a short identifier such as ru or eng.

It is clear that when programming such a configuration, 1C lines can also be multilingual. To do this, it is possible to create such a 1C line by specifying through; options by language identifier:

Variable = "ru=""Hello, world! ""; en=""Hello, world! """;

If you use the 1C line formed this way as usual, then it will be what is written in it. In order for the system to split it into two options and use the desired one, you need to use the НStr() function:

//correct for bilingual configurations
Report(NStr(Variable));

Props with line type 1C

The attribute is a field in the 1C directory/document. It differs from a variable in a program in the 1C language in that for the attribute its type is precisely indicated (number, 1C string, etc.). If you need to refresh your memory of what a prop is, watch the lesson on.

If you specify the type of attribute - line 1C, then you must additionally specify the parameters.

1C lines come in unlimited length (indicated as length = 0) and limited length, indicating the exact number of characters. 1C lines of unlimited length are stored in a separate SQL table, so their use is less productive than limited.

That is why the use of 1C strings of unlimited length has its limitations - it is not possible to use them everywhere. For example, it is not allowed as a document number, reference code, or measurement.

Working with 1C strings

There are several built-in functions of the 1C platform for working with strings.

  • AbbrLP (“Incredible, but true!”)
    Removes extra spaces from the 1C line. Can also be used to convert any types to a 1C string (for example, numbers).
  • Variable = "Vasya" + AbbrLP(" plus") + "Olya"; //there will be "Vasya plus Olya"
    An example of summing several 1C string values. The result will be one line 1C.
  • Variable = Lev("Music", 2); //will be "Mu"
    Variable = Medium("Music", 2, 2); //there will be "threat"
    Variable = Rights("Music", 2); //there will be "ka"
    Various options for obtaining a substring from a 1C string.
  • Variable = Find("Music", "zy"); //there will be 3
    Search for a substring in string 1C, starting with character 1.
  • Variable = StrLength("Music"); //there will be 6
    Returns the number of characters in the 1C line.
  • Report("Hello") //in the message window at the bottom of the 1C window
    Alert("Hello") //popup dialog
    Status("Hello") //in the status display line at the bottom left
    .

Bringing objects to line 1C

As you know, the most popular format for exchanging structured information at present is XML. Even latest version MS Office Word and Excel save files in this format (docx and xlsx, respectively, change the extension to zip, open in an archiver).

The 1C platform for data exchange provides several options, the main one of which is also XML.

1. The simplest method is to use the Abbreviation() or String() function. You can use the REPRESENTATION() function in the request body. The result of their action is the same - they generate a string representation of any 1C object for the user.

For a directory by default, this will be its name. For a document – ​​document name, number and date.

2. Any 1C object (with restrictions) can be converted to XML and vice versa. The conversion process is called serialization.

StringViewXml = XMLString(Value); //get XML from 1C value
Value1C = XMLValue(Type("DirectoryLink.Nomenclature"),TypeStringXml); //get the 1C value from the XML string, you must specify the 1C type that should be received

3. There is the 1C platform’s own way to convert any 1C object into a string. It migrated from version 1C 7.7. This format is not understood by other programs, but other 1C understands it, which makes it easy to use it for exchange between 1C databases.

Row = ValueInRowInt(Value1C); //get string 1C from value 1C
ValueVFile("C:\MyFile.txt", Value1C); //another option, we get a file with a saved string from the 1C value
Value1C = ValueFromStringInt(String); //back from line 1C
Value1C = ValueFile("C:\MyFile.txt"); //back from file

Editing 1C lines on the form

In addition to working with 1C strings in a program in the 1C language, of course I would like the user to be able to edit them. There are several possibilities for this:

1. The easiest way is to request the entry of a 1C line on demand. This method is used when teaching 1C programming; in life it is used much less often (but it is used!).

Variable = "";
Row = EnterValue(Variable, "Enter Full Name");

2. To display the details of a 1C object (directory/document) or form details (see), an input field is most often used. This is the most common tool in 1C for the user to work with editing fields.

3. The capabilities of the input field can be expanded (see properties of the input field, right click on it, more details):

  • Checkbox Multiline editing mode
  • Advanced editing checkbox (available if the previous checkbox is checked)
  • Checkbox Password mode (see).

4. If all the capabilities of the input field are not enough for you, there is a built-in editor. To add it to the form, you need to add Field to the Form/Insert control menu text document. In its properties you can specify its operating mode – the Extension property.

A text document field cannot be associated directly with data. It is necessary to write a function in the OnOpen() event handler of the form (see):

Form Elements.ElementNameTextDocumentField.SetText(StringValue); //here ValueString is the text received, for example, from the attribute

And in the save handler - for example, in the Save button - add a save:

ValueString = FormElements.ElementNameTextDocumentField.GetText(); //ValueThe line here is the attribute where we save the value

5. In 1C version 8.2.11, in controlled forms, appeared new opportunity 1C line representation – Formatted document field.


Similar to the field of a text document, you must set it when opening it and write it down when saving it yourself using the program.

  • In the 1C object whose form we are creating (directory, document, processing, etc.) - add an attribute with the Value Storage type
  • In the OnReadOnServer() function we set the text from the attribute

    //here the Attribute is the added attribute of the 1C object
    //here FormattedDocument is the name of the field on the form for editing
    &On server

    FormattedDocument = CurrentObject.Attributes.Get();
    End of Procedure

  • In the BeforeWritingOnServer() function or using the button, we will write the text from the field

    &On server
    Procedure When ReadingOnServer(CurrentObject)
    CurrentObject.Props = NewValueStorage(FormattedDocument);
    End of Procedure

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

Type variable values line are enclosed in double quotes. Multiple Variables of this type can be folded.

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

Eventually Per3 will mean " Word 1 Word 2″.

In addition, 1C:Enterprise 8 systems provide functions for working with strings. Let's look at the main ones:

EnterString(<Строка>, <Подсказка>, <Длина>, <Многострочность>) — the function is designed to display a dialog box in which the user can specify the value of a variable of type Line. Parameter <Строка> is required and contains the name of the variable into which the entered string will be written. Parameter <Подсказка> optional - this is the title of the dialog box. Parameter <Длина> optional, shows the maximum length of the input string. Defaults to 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.

You can enter a string if you know the character code in Unicode:

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

Letter= Symbol(1103) ;

// I

There is also an inverse function that allows you to find out the code of a symbol.<Строка>, <НомерСимвола>) — SymbolCode(

returns the Unicode number of the specified character as a number.

Text case conversion functions:<Строка>) VReg(

— Converts all characters in a string to uppercase.<Строка>) NReg(

— Converts all characters in a string to lowercase.<Строка>) TReg(

— converts all characters in the string to title case. That is, the first letters in all words are converted to upper case, and the remaining letters are converted to lower case.

Functions for searching and replacing characters in a string:<Строка>, <ПодстрокаПоиска>) Find(

Find ("String" , "oka" ) ;

// 4<Строка>, <ПодстрокаПоиска>, <НаправлениеПоиска>, <НачальнаяПозиция>, <НомерВхождения>) StrFind( — finds the character number of the occurrence of the search substring, the occurrence number is indicated in the corresponding parameter. In this case, the search begins with the character whose number is specified in the parameter InitialPosition.

Searching is possible from the beginning or the end of the string. For example: Number4 Occurrences = Str Find ("Defensiveness"

, "about" ,Search Direction. From Start, 1, 4);<Строка>, <ПодстрокаПоиска>, <ПодстрокаЗамены>) // 7

StrReplace(

– finds all occurrences of the search substring in the source string and replaces it with the replacement substring.<Строка>) StrReplace ("String" , "oka" , "" ) ; // 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 (<Строка>, <ЗначениеПодстановки1>…<ЗначениеПодстановкиN> — "Study, study and study again" , "study" , "" ) ; // 3 StrTemplate(

substitutes parameters into a string by number. The line must contain substitution markers of the form: “%1..%N”. Marker numbering starts from 1. If the parameter value Undefined, "1" , "2" ) ; , an empty string is substituted.

StrTemplate (

"Parameter 1 = %1, Parameter 2 = %2"<Строка>, <ЧислоСимволов>) // Parameter 1= 1, Parameter 2 = 2

String conversion functions:<Строка>, <ЧислоСимволов>) A lion(

– returns the first characters of a string.<Строка>, <НачальныйНомер>, <ЧислоСимволов>) Right(<ЧислоСимволов>– returns the last characters of a string.<НачальныйНомер>.

Wednesday(<Строка>) – returns a string of length

, starting from symbol<Строка>) AbbrL(

trims non-significant characters to the left of the first significant character in the string.<Строка>) Abbr(

— cuts off insignificant characters to the right of the last significant character in the line.<Строка>, <НомерСтроки>) AbbrLP(

– cuts off insignificant characters to the left of the first significant character in the line and to the right of the last significant character in the line.

StrGetString(<Строка>) – Gets a multiline string by number.

Other features:<Строка>) StrLength(

– returns the number of characters in the string.<Строка1>, <Строка2> ) StrNumberRow( – returns the number of lines in a multiline string. A line is considered new if it is separated from the previous one by a newline character. StrCompare(

  • – compares two strings in a case-insensitive manner. A function works like an object
  • Comparison of Values
  • . Returns:

1 - if the first line is greater than the second

There are few mechanisms for working with strings in 1C queries. First, the lines can be added. Secondly, you can take a substring from a string. Thirdly, strings can be compared, including by pattern. That's probably all that can be done with strings.

String addition

To add rows in a query, the “+” operation is used. You can only add strings of limited length.

SELECT "Name: " + Counterparties. Name AS Column 1 FROM Directory. Counterparties AS Counterparties WHERE Counterparties. Link = &Link

Substring function

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

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

If the length of the string 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 a string attribute meets certain criteria, we compare it:

SELECT Counterparties. Name AS Column 1 FROM Directory. Counterparties AS Counterparties WHERE Counterparties. Name = "Gazprom"

But what if you need a more subtle comparison? Not just equality or inequality, but similarity to a certain pattern? This is exactly what the SIMILAR function was created for.

LIKE — Operator for checking a string for similarity to a pattern. Analogue of LIKE in SQL.

The SIMILAR operator allows you to compare the value of the expression specified to the left of it with the pattern string specified to the right. The value of the expression must be of type string. If the value of the expression matches the pattern, 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 meaning different from the string character:

  • % (percent): a sequence containing any number of arbitrary characters;
  • _ (underscore): one arbitrary character;
  • […] (V square brackets one or more characters): any single character listed inside square brackets. The enumeration may contain ranges, for example a-z, meaning an arbitrary character included in 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 one of the listed characters needs to be written as itself, then it must be preceded by<Спецсимвол>. Myself<Спецсимвол>(any suitable symbol) is defined in the same statement after keyword SPECIAL SYMBOL.