3

In QGIS 3.18. I am looking for a field calculator expression able to return the values of a string (comma separated) in Field B which are not* also values of a string in Field A. For example:

  • Field A: 2,4,6,8,10
  • Field B: 1,2,3,4,5
  • Field C (desired result of expression): 1,3,5

I suppose this will be a situation for string_to_array and then an array function, but array_distinct returns distinct values of one single array; perhaps there is a way to structure the expression such that it will compare the 2 cells, but I've not yet found it.

asked Sep 19, 2021 at 10:44

2 Answers 2

3

Use this expression:

array_to_string (
 array_remove_all(
 array_foreach (
 string_to_array(field_B),
 if (
 array_contains (string_to_array(field_A),@element),
 '',
 @element
 )
 ), 
 ''
 )
)

enter image description here

answered Sep 19, 2021 at 11:21
3

Great answer by @Babel!

Another option would be:

regexp_replace(replace("Field B", string_to_array("Field A"), ''), ',,', ',')

enter image description here

The core part of the expression is replace("Field B", string_to_array("Field A"), ''), but it will produce 1,,3,,5 so regexp_replace(~~~, ',,', ',') was added to remove doubled commas.

answered Sep 19, 2021 at 11:28
2
  • I knew there was a simpler solution to that... great! Commented Sep 19, 2021 at 13:10
  • @Babel I believe your solution has much wider application than this! Commented Sep 20, 2021 at 2:51

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.