7

I have a string field. Which requests to put the letter F after the number to all positive digits, and the letter B after minus digits and to delete the sign -.

Finally, I want a result like this:

enter image description here

3 Answers 3

10

Use this expression:

array_to_string(
    array_foreach(
        string_to_array( LineCodes, ',' ),
        if(
            left( @element, 1 ) = '-',
            substr( @element, 2 ) + 'B',
            @element + 'F'
            )
        )
    )

string_to_array : splits string into an array using comma
array_foreach : runs given expression for every element in array
array_to_string : concatenates elements into a string separated by comma

2
  • How do I rewrite this expression for the opposite process? From 8F_16B_17B to 8,-16,-17
    – Ivan M
    Commented Dec 25, 2020 at 14:20
  • You'd better use a regular expression for this. I don't have enough experience on regular expressions. You can ask this as another question. Commented Dec 25, 2020 at 14:28
10

You can define your own custom expression function in Python and then use it in the Field Calculator.

@qgsfunction(args='auto', group='Custom', usesGeometry=False)
def custom(input, feature, parent):
    if input is None:
        return None
    numbers = [int(num) for num in input.split(',')]
    def f(num):
        if num > 0:
            return '{}F'.format(num)
        return '{}B'.format(abs(num))
    result = map(f, numbers)
    return ','.join(result)
  1. Define it by running the code above as a script in the Python Console:

    enter image description here

  2. Use it in the Field Calculator:

    enter image description here

0
9

You may also try the following expression:

array_to_string(
    array_foreach(
        string_to_array("test"),
        if(
            to_int(@element)>0,
            @element||'F',
            abs(@element)||'B'
            )
        )
    )

See, for example below

result

P.S. IMHO using the regexp_replace() is pointless because more changes have to be applied rather than substitutions.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.