简体   繁体   中英

Regex to match the rest of string after the 4th character

Here's the list of my random numbers

r7l5ndecvz9
0qb6rtxsd6ui
dj5iuzpq5vn
rysquf0jkek
435vw5h2qag

And what I want to do is to match or trim the rest after the number of characters (lets say 4), and I want to output as this:

r7l5
0qb6
dj5i
rysq
435v

See, I only want to match the rest of the characters after the 4th character. I tried this regex expression .{4}\b but it only matches the last 4 characters. I also tried this expression ^(\S\S\S\S) but it only matches the first 4 characters. I want to match the rest AFTER the 4th character. Any idea what I'm doing wrong?

Given the sample inputs and outputs, you want to capture the first four characters. The regex for this is ^(.{4})

The caret matches the start of the line, the dot matches any character, the 4 in braces indicates 4 occurrences, and the parentheses capture the result for later access.

Here's working Python code:

import re
inputs = ['r7l5ndecvz9','0qb6rtxsd6ui','dj5iuzpq5vn','rysquf0jkek','435vw5h2qag']
for str in inputs:
    match = re.search('^(.{4})',str)
    print(match.group(0))

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