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:
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
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)
Define it by running the code above as a script in the Python Console:
Use it in the Field Calculator:
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
P.S. IMHO using the regexp_replace()
is pointless because more changes have to be applied rather than substitutions.