There is a task: Take the IP and Port from the line in the .csv file (example below, first IP, then port)

1.33.3.146,9001,,fwioetwg4utghw4ignc,Fast Running Stable Valid,447,reject,1-65535,0 

I wrote Regex to take IP, Port, but together with this, it also takes "1-65535.0", but I do not need it.

Regex:

 \d{1,3}.\d{1,3}.\d{1,3}.\d{1,3},(\d{1,5}) 

Tell me what to add to my Regex? Thank!

  • You do not need regulars. CSV has a strictly defined format, just parse it. In the simplest case, you can simply break the line by a comma - Andrew NOP
  • Well, just right at the very beginning - add to the regexp the symbol of the beginning of the line ^ . And yet, just a point in regexp - this is never a point symbol ... - Akina
  • /(?<!\d)\d{1,3}(?:\.\d{1,3}){3},(\d{1,5})(?!\d)/ ( /(?<!\d)\d{1,3}(?:\.\d{1,3}){3},(\d{1,5})(?!\d)/ , (( /(?<!\d)\d{1,3}(?:\.\d{1,3}){3},(\d{1,5})(?!\d)/ ( /(?<!\d)\d{1,3}(?:\.\d{1,3}){3},(\d{1,5})(?!\d)/ , demo . - Wiktor Stribiżew
  • Gentlemen, thank you! @Akina, your comment about the point is absolutely true, I missed this point. Corrected. - BabyCoder
  • Theoretically, after quoting, the point "1-65535.0" should cease to be recognized by regexp. - Akina

1 answer 1

Screen dots that are not metacharacters that find any character. Use a more accurate IP address template :

 (?<!\d)((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}),(\d{1,5})(?!\d) 

See the regular expression demo .

Details

  • (?<!\d) - right before the match there should not be a digit
  • ( - the beginning of exciting trap # 1
  • (?: - the beginning of the untagged group, in which the range of the IP address block is defined:
    • 25[0-5]| - 25 , followed by a digit from 0 to 5
    • 2[0-4][0-9]| - 2 , followed by a digit from 0 to 4 , and then one any digit
    • [01]?[0-9][0-9]? - 0 or 1 (optional, 1 or 0 times), then 1 or 2 digits
  • ) - the end of the group (trappings)
  • (?: - the beginning of the non-capturing group (which will be repeated 3 times)
    • \. - point
    • (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) - the template described above
  • ){3} - 3 reps
  • ) - the end of an exciting deception
  • , - comma
  • (\d{1,5}) - exciting disguise number 2: 1-5 digits
  • (?!\d) - immediately after the match there should not be a digit.