简体   繁体   中英

regex word boundaries

I am trying to write a regex to match a string with the START of ALL words in a string.

It would be used to lookup a city via the name or the zipcode (in a city and zipcode concatenated string) when the user types one character (or string).

The problem is that it also matches the END of the city (which is unwanted...) I am using the following regex :

patt = new RegExp('\\b' + searchchar, 'i')

eg :

  • teststring : "Sint-niklaas (9100)"
  • char typed : 's'
    => unwanted matches S int-niklaa s (9100) <== problem :-)
    => wanted matches S int-niklaas (9100)

  • char typed : '9'
    => wanted matches Sint-niklaas ( 9 100) <== ok

I think you are looking for that:

patt = new RegExp('^(?:[^(]+\\()?' + searchchar, 'mi');

^ is an anchor for the start of the string line (with the m modifier). When you enter a letter, since there are only digits inside parenthesis, the optional non-capturing group fails and the letter can only be at the start. When a digit is entered, the optional group succeeds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM