Home > front end >  Regex to match english character range between a comma
Regex to match english character range between a comma

Time:10-07

I am crrently trying to sort through a file and need a regex for the following scenario:

A line should have the characters from A-Z a-z 0-9 or " " "_" then it is going to be separated by a single , and then it should match the A-Z a-z 0-9 or " " "_" again. But it should not accept a line if there are any other characters before or after it.

So this should be valid:

123 45, Amogus
1234, Al Amogus9_

But this should be not:

1235, AMogus,,,,,,,,,,,,,,,
susus
s, s, s
.12, sus.

I currently have this regex [A-Za-z0-9_" "] ,[A-Za-z0-9_" "] but unfortunately it does noot exclude any special characters before or after the string

CodePudding user response:

It seems that you are looking for anchors, ^ and $ which mark begin and end of the string:

^[A-Za-z0-9_ ] ,[A-Za-z0-9_ ] $

here

^              - beginning of the string
[A-Za-z0-9_ ]  - one or more letters, digits, _ or spaces (' ')
,              - comma ','
[A-Za-z0-9_ ]  - one or more letters, digits, _ or spaces (' ')
$              - end of the string 

So you have pattern which should match the whole string not an arbitrary part of it. Note, that space (' ') is an ordinary symbol in regex, no quotation marks are required.

Fiddle yourself

  • Related