Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for a sentence syntax

Tags:

regex

I am trying to separate a String into different parts that match a specif syntax.

The String I am using as example is Username 5/5, Version: 1.0 This is a custom message Sep 25, 2018.

Currently I have this Regex (\w+) ([0-9]\/[0-9]), (\w+): ([0-9][.][0-9][.]?[0-9]?) which gives me The username, the 5/5, the word version and the version 1.0.

First, how can I ignore the (\w+)? Since it'll always be version and I only need the number after. Second question, is it possible to get the big message after the version, then get the date after it?

Output needed:
Username
5/5
1.0
This is a custom message
Sep 25, 2018

like image 218
Matt Avatar asked Mar 16 '26 23:03

Matt


2 Answers

You may use

/^(\w+)\s+(\d+\/\d+),\s+\w+:\s*(\d+(?:\.\d+){1,2})\s*(.*?)\s*([a-zA-Z]+\s*\d{1,2},\s*\d{4})$/

See the regex demo

Details

  • ^ - start of string
  • (\w+) - Group 1 (username): one or more letters, digits or _
  • \s+ - 1+ whitespaces
  • (\d+\/\d+) - Group 2 (5/5)
  • ,\s+ - a comma and 1+ whitespaces
  • \w+: - 1+ word chars followed with :
  • \s* - 0+ whitespaces
  • (\d+(?:\.\d+){1,2}) - Group 3 (version number):
    • \d+ - 1+ digits
    • (?:\.\d+){1,2} - 1 or 2 sequences of a . followed with 1+ digits
  • \s* - 0+ whitespaces
  • (.*?) - Group 4 (message): any 0+ chars, as few as possible
  • \s* - 0+ whitespaces
  • ([a-zA-Z]+\s*\d{1,2},\s*\d{4}) - Group 4 (date):
    • [a-zA-Z]+ - 1+ ASCII letters
    • \s* - 0+ whitespaces
    • \d{1,2} - 1 to 2 digits
    • ,\s* - a comma and 0+ whitespaces
    • \d{4} - 4 digits
  • $ - end of string.
like image 51
Wiktor Stribiżew Avatar answered Mar 18 '26 12:03

Wiktor Stribiżew


Try (.*)\s(\d\/\d),\s*Version:\s*(\d+\.\d+)\s*(.+?)\s*(\w{3} \d{1,2}, \d{4})

Capture the groups 1,2,3,4,5 to get the output you needed.

Regex

like image 33
Nambi_0915 Avatar answered Mar 18 '26 13:03

Nambi_0915



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!