Python Forum
Searching for digits followed by a string.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Searching for digits followed by a string.
#1
Hello.

Given an input like "1234abd-alknfsdan-asjkldn-asd" I want to be able to see if there are 4 digits at the start followed by a specific substring. In this case we will use abd. As in the given example, I want to be able to see that the string starts with 4 digits, then is followed by "abd". In this case it passes.
So far I can only match if there are digits in the string at all, not worrying about where. How can I go about this?
import re

string = "1234ict-asdasd-asdasd"

print(bool(re.search(r'\d', string)))
Thanks :)

P.S.
Just to clarify, these are the requirements:
  • 4 (no more, no less) digits at the start of the string.
  • Followed by a given string, it can be anything I want
Reply
#2
Using regular expression in such trivial problem is overkill.

def check_string(a, fbs='mystring'):
    return a[:4].isdigit() and a[4:].startswith(fbs)

check_string("1234mystringgoeshere") # True
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  splitting file into multiple files by searching for string AlphaInc 2 929 Jul-01-2023, 10:35 PM
Last Post: Pedroski55
  Finding First Digits in String giddyhead 4 1,400 Aug-17-2022, 08:12 PM
Last Post: giddyhead
  Single digits seem to be greater than double digits Frosty_GM 4 3,556 Nov-20-2020, 10:13 AM
Last Post: DeaD_EyE
  Please support regex for version number (digits and dots) from a string Tecuma 4 3,233 Aug-17-2020, 09:59 AM
Last Post: Tecuma
  Searching string in file and save next line dani8586 2 2,332 Jul-10-2020, 09:03 AM
Last Post: dani8586
  Unexpected output when searching for a string from os.popen output FujiJean 3 3,098 Oct-02-2018, 11:39 AM
Last Post: volcano63
  Input a number with any number of digits and output it in reverse order of digits. sarada2099 6 6,707 Mar-12-2017, 05:45 PM
Last Post: Ofnuts
  Fast method of searching a string in a multi-dimension array? draems 6 6,037 Feb-20-2017, 01:02 PM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020