البرمجة

استخراج الأرقام الأولى من النص بواسطة Regex

To extract only the first 4 digits from each line of your input using Python’s regex, you can use the re module. Here’s a sample code that demonstrates how to achieve this:

python
import re # Your input string input_string = """ +1511 0716 +4915 CZECHY +3815/0616 PORT MO, AO _3615 USA *, SUV run on flat +4515 PORT SUV *, SUV +3215 USA *, SUV +4414 +4815 NIEM _0616 NIEM * / MO +2115 NIEM J """ # Regex pattern to match 4 digits at the beginning of each line pattern = r"^\d{4}" # Find all matches matches = re.findall(pattern, input_string, re.MULTILINE) # Print the matches for match in matches: print(match)

This code will output the first 4 digits from each line in your input string.

المزيد من المعلومات

بالطبع، يمكنني توضيح المزيد حول كيفية عمل الرموز والتعابير العادية في Python لتناسب احتياجاتك. تعبير الرجوع إلى البداية ^ يستخدم للبحث عن النصوص التي تبدأ بها السلسلة، و\d تعبير عن الأرقام العشرية، و{4} يحدد عدد مرات تكرار العنصر الذي يسبقه (في هذه الحالة، 4 مرات للأرقام العشرية). تم استخدام re.MULTILINE لجعل البحث يعمل على كل سطر منفصل في النص.

إذا كنت بحاجة إلى مزيد من التوضيح أو لديك استفسارات أخرى، فلا تتردد في طرحها!

زر الذهاب إلى الأعلى