Nice programing

쉼표로 구분 된 목록에 대한 정규식

nicepro 2020. 11. 23. 19:59
반응형

쉼표로 구분 된 목록에 대한 정규식


다음과 같이 쉼표로 구분 된 목록의 유효성을 검사하는 정규식은 무엇입니까?

12365, 45236, 458, 1, 99996332, ......

다음과 같은 방법으로 수행하는 것이 좋습니다.

(\d+)(,\s*\d+)*

하나 이상의 요소를 포함하는 목록에서 작동합니다.


이 정규식은 내용에 관계없이 쉼표로 구분 된 목록에서 요소를 추출합니다.

(.+?)(?:,|$)

쉼표를 다른 것으로 바꾸면 모든 구분 기호에서 작동합니다.


정확한 요구 사항에 따라 약간 다릅니다. 나는 모든 숫자, 모든 길이, 숫자는 선행 0을 가질 수 없으며 쉼표 또는 소수점을 포함 할 수 없다고 가정합니다. 개별 숫자는 항상 쉼표와 공백으로 구분되며 마지막 숫자 뒤에는 쉼표와 공백이 없습니다. 이 중 하나라도 잘못되면 솔루션이 단순화됩니다.

([1-9] [0-9] *, []) * [1-9] [0-9] *

내가 그것을 정신적으로 만든 방법은 다음과 같습니다.

[0-9]  any digit.
[1-9][0-9]*  leading non-zero digit followed by any number of digits
[1-9][0-9]*, as above, followed by a comma
[1-9][0-9]*[ ]  as above, followed by a space
([1-9][0-9]*[ ])*  as above, repeated 0 or more times
([1-9][0-9]*[ ])*[1-9][0-9]*  as above, with a final number that doesn't have a comma.

쉼표로 구분 된 중복 항목 일치 :

(?<=,|^)([^,]*)(,\1)+(?=,|$)

참조 .

이 정규식은 쉼표로 구분 된 목록의 값을 분할하는 데 사용할 수 있습니다. 목록 요소는 인용되거나 인용되지 않거나 비어있을 수 있습니다. 한 쌍의 따옴표 안의 쉼표는 일치하지 않습니다.

,(?!(?<=(?:^|,)\s*"(?:[^"]|""|\\")*,)(?:[^"]|""|\\")*"\s*(?:,|$))

참조 .


/^\d+(?:, ?\d+)*$/

나는 이것을 각 항목의 앞에 밑줄없이 영숫자 여야하는 항목 목록에 사용했습니다.

^(([0-9a-zA-Z][0-9a-zA-Z_]*)([,][0-9a-zA-Z][0-9a-zA-Z_]*)*)$

이것은 당신에게 중요한 경우 줄의 시작 또는 끝에서 불필요한 쉼표를 거부합니다.

((, )?(^)?(possible|value|patterns))*

possible|value|patterns허용 된 값과 일치하는 정규식으로 바꿉니다 .


안전을 위해 언어를 지정하고 싶을 수도 있지만

(\d+, ?)+(\d+)?

일해야 해


다음과 같이 이스케이프 된 쉼표로 인코딩 된 사전 / 해시 테이블을 구문 분석하는 데 약간 다른 요구 사항이있었습니다.

"1=This is something, 2=This is something,,with an escaped comma, 3=This is something else"

나는 이것이 많은 정규식 복잡성을 피하는 트릭과 함께 우아한 솔루션이라고 생각합니다.

if (string.IsNullOrEmpty(encodedValues))
{
    return null;
}
else
{
    var retVal = new Dictionary<int, string>();
    var reFields = new Regex(@"([0-9]+)\=(([A-Za-z0-9\s]|(,,))+),");
    foreach (Match match in reFields.Matches(encodedValues + ","))
    {
        var id = match.Groups[1].Value;
        var value = match.Groups[2].Value;
        retVal[int.Parse(id)] = value.Replace(",,", ",");
    }
    return retVal;
}

I think it can be adapted to the original question with an expression like @"([0-9]+),\s?" and parse on Groups[0].

I hope it's helpful to somebody and thanks for the tips on getting it close to there, especially Asaph!


In JavaScript, use split to help out, and catch any negative digits as well:

'-1,2,-3'.match(/(-?\d+)(,\s*-?\d+)*/)[0].split(',');
// ["-1", "2", "-3"]
// may need trimming if digits are space-separated

The following will match any comma delimited word/digit/space combination

(((.)*,)*)(.)*

참고URL : https://stackoverflow.com/questions/1396084/regex-for-comma-delimited-list

반응형