I have origin-destination lines and I'm looking for intra-city lines or lines whose origin and destination are in the same city.

A sample intra-city feature would be "Quezon_City to Quezon_City" and inter-city would be "Quezon_City to CALOOCAN_CITY".

I'd like some help in writing an expression that selects all features whose string before "to" is the same with the string after it using Python or Expression Builder.

  • Yes. The pattern is 'origin' to 'destination' for all features. – BallpenMan Sep 21 '20 at 7:08
  • It works! Thank you!!! Saved me a lot of time (and errors) – BallpenMan Sep 21 '20 at 7:16

Currently I have two ideas how to tackle your issue

Case 1. Only working with an Attribute table where you will need to use the following expression

if(left("test",regexp_match("test",'\\ to ')-1) = right("test",regexp_match("test",'\\ to ')-1), true, false)

Case 2. Working with geometries of lines and polygons, of course if you have cities as polygons.

So, geometrically check if starting and ending points of the "origin-destination"-lines are both within those polygons. In PostGIS-interpretation it might be something like

st_within(start_point(line.geometry), polys.geometry)
AND st_within(end_point(line.geometry), polys.geometry)

@Taras has already given an answer that solves your problem. Let me give you another one using PyQGIS.

I have an attribute table with 2 fields: descriptions which corresponds to your text and equal to indicate whether the text before to is identical to the text after to.

layer = iface.activeLayer() # your layer

# Loop on each feature of the layer
for feat in layer.getFeatures():
    feat_text = feat["description"] # your text
    pos_to = feat_text.find("to") # find the position of the word "to"
    before_to = feat_text[:pos_to].replace(" ", "") # Extract the text before the previous position and remove blank lines
    after_to = feat_text[pos_to+2:].replace(" ", "") # Extract the text after 
    # Update of the "equal" field depending the text before and after
    if before_to == after_to:
        feat["equal"] = 'yes'
        feat["equal"] = 'no'

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.