QGIS – Extracting Text Before First Slash Using Regular Expressions

qgisregexstring

I have a database of motorway junctions which are named like this:

  • M90 J8/A91/B996
  • M90 J1/A90/A921/A985(T)
  • M9 J1A

There is significant variability in the length of the strings but they all follow the same basic pattern of Motorway ID Junction Number / Link Road IDs

How do I extract everything before the first forward slash i.e. the Motorway ID and Junction Number?

  • M90 J8
  • M90 J1
  • M9 J1A

I've been trying to use regex_substr based on other answers on here like this: regexp_substr( "NAME", '^(.+)/') but this extracts everything before the last forwardslash. How can I alter it to get the text before the first slash?

Best Answer

QGIS' regex engine doesn't support non greedy matches (yet), so it'll always return the longest possible match. Try

regexp_substr( "NAME", '^[^/]+')

That should return all characters from the start of the string which aren't /s.