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


Use this expression:

        string_to_array( LineCodes, ',' ),
            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

  • Thank you so much! Expression works great! – Ivan M Dec 23 '20 at 12:02
  • How do I rewrite this expression for the opposite process? From 8F_16B_17B to 8,-16,-17 – Ivan M Dec 25 '20 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. – Kadir Şahbaz Dec 25 '20 at 14:28

You can define your own custom expression function in Python and then use it in 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 Python console: enter image description here

  2. Use it in the field calculator: enter image description here

  • Thank you! This is an interesting solution of the problem! – Ivan M Dec 23 '20 at 12:04

You may also try the following expression

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

See, for example below


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

  • 1
    Thank you! This is very useful – Ivan M Dec 23 '20 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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