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

Taras
35.8k5 gold badges77 silver badges152 bronze badges
asked Dec 23, 2020 at 8:57

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

Taras
35.8k5 gold badges77 silver badges152 bronze badges
answered Dec 23, 2020 at 10:13
2
  • How do I rewrite this expression for the opposite process? From 8F_16B_17B to 8,-16,-17 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

Taras
35.8k5 gold badges77 silver badges152 bronze badges
answered Dec 23, 2020 at 9:35
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.

answered Dec 23, 2020 at 10:45
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.