简体   繁体   中英

Regex to sort files into folders alphabetically by surname?

I 'm trying to find a way to write a regex to sort files into separate folders alphabetically based on surname. The file names all start with a name but written "first name last name" so I need an expression that will match the first letter of the last word before the first deliminator " - ". For example

 John M. Allen - job 00 - october.txt

Should match the "A" in Allen and all the other last names beginning with "A" so I can use File Renamer to then move them to a folder called "A"

I'm fairly new to regex and dont know how to go about this one. I'm using File Renamer 6.0.1 which is in JS.

Try this:

\b[A-Z](?=[a-z]+\s-\s)

See this.

This may look at bit complex, but it's not if you understand all the pieces (the \\b means match a word boundary, just google 'word boundaries regex' to learn more). The ?= is a look-ahead assertion. I've added a word boundary and some more details in order to avoid bad matches, suppose you had A before the 00 - october part, if I didn't use [az]+ and instead \\w+ then that would match as well which is not what you want.

Not particularly robust, given that it won't work for two last names or any funky punctuation, but this should should get you started anyway:

(\w)\w+(?<=\w) - 

Example

The first letter of the last name is in the first capture group; depending on what language you're using you'll need to sort out how to reference it.

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