C # 정규식은 예제와 일치
다음 텍스트를 사용하여 값을 얻으려고하는데, Regex로 할 수 있다고 생각하십니까?
입력
Lorem ipsum dolor sit % download % # 456 amet, consectetur adipiscing % download % # 3434 elit. Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra % download % # 298. Aenean dapibus nisl % download % # 893434 id nibh auctor vel tempor velit blandit.
산출
456
3434
298
893434
미리 감사드립니다.
"% download % #"토큰이 앞에 오는 숫자 값을 가져 오려고합니까?
이 패턴을 시도하십시오.
(?<=%download%#)\d+
작동합니다. 나는 생각하지 않는다 #
또는 %
.NET 정규식에 특수 문자가 있지만, 당신은에있는 하나처럼 백 슬래시를 이스케이프 것 \\
또는 사용 그대로 문자열을 전체 패턴 :
var regex = new Regex(@"(?<=%download%#)\d+");
return regex.Matches(strInput);
여기에서 테스트 됨 : http://rextester.com/BLYCC16700
참고 : 결과 (?<=...)
에 포함하지 않고 %download%#
그 뒤의 숫자 만 포함하기를 원하기 때문에 lookbehind 어설 션 이 중요 합니다. 그러나 캡처하려는 각 문자열 앞에 예제가 필요한 것으로 보입니다. lookbehind 그룹은 입력 문자열에 있는지 확인하지만 반환 된 결과에는 포함하지 않습니다. 여기에서 둘러보기 주장에 대해 자세히 알아보세요.
내가 보는 다른 모든 응답은 괜찮지 만 C #은 명명 된 그룹을 지원합니다!
다음 코드를 사용합니다.
const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";
static void Main(string[] args)
{
Regex expression = new Regex(@"%download%#(?<Identifier>[0-9]*)");
var results = expression.Matches(input);
foreach (Match match in results)
{
Console.WriteLine(match.Groups["Identifier"].Value);
}
}
다음과 같은 코드는 의 결과가 위와 같이 인덱싱하는 명명 된 그룹의 일부 (?<Identifier>[0-9]*)
임을 지정합니다 [0-9]*
.match.Groups["Identifier"].Value
public void match2()
{
string input = "%download%#893434";
Regex word = new Regex(@"\d+");
Match m = word.Match(input);
Console.WriteLine(m.Value);
}
여기에있는 대부분의 게시물이 여기에 필요한 내용을 설명한 것 같습니다. 그러나-파싱하는 내용에 따라 더 복잡한 동작이 필요할 수 있습니다. 귀하의 경우에는 더 복잡한 구문 분석이 필요하지 않을 수 있지만 추출하는 정보에 따라 다릅니다.
정규식 그룹을 클래스의 필드 이름으로 사용할 수 있으며 그 후에 다음과 같이 작성할 수 있습니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
public class Info
{
public String Identifier;
public char nextChar;
};
class testRegex {
const string input = "Lorem ipsum dolor sit %download%#456 amet, consectetur adipiscing %download%#3434 elit. " +
"Duis non nunc nec mauris feugiat porttitor. Sed tincidunt blandit dui a viverra%download%#298. Aenean dapibus nisl %download%#893434 id nibh auctor vel tempor velit blandit.";
static void Main(string[] args)
{
Regex regex = new Regex(@"%download%#(?<Identifier>[0-9]*)(?<nextChar>.)(?<thisCharIsNotNeeded>.)");
List<Info> infos = new List<Info>();
foreach (Match match in regex.Matches(input))
{
Info info = new Info();
for( int i = 1; i < regex.GetGroupNames().Length; i++ )
{
String groupName = regex.GetGroupNames()[i];
FieldInfo fi = info.GetType().GetField(regex.GetGroupNames()[i]);
if( fi != null ) // Field is non-public or does not exists.
fi.SetValue( info, Convert.ChangeType( match.Groups[groupName].Value, fi.FieldType));
}
infos.Add(info);
}
foreach ( var info in infos )
{
Console.WriteLine(info.Identifier + " followed by '" + info.nextChar.ToString() + "'");
}
}
};
이 메커니즘은 C # 리플렉션을 사용하여 값을 클래스로 설정합니다. 그룹 이름은 클래스 인스턴스의 필드 이름과 일치합니다. Convert.ChangeType은 어떤 종류의 쓰레기도 허용하지 않습니다.
행 / 열 추적을 추가하려면 행에 대한 정규식 분할을 추가 할 수 있지만 for 루프를 그대로 유지하려면 모든 일치 패턴에 명명 된 그룹이 있어야합니다. (그렇지 않으면 열 인덱스가 잘못 계산됩니다)
결과는 다음과 같습니다.
456 followed by ' '
3434 followed by ' '
298 followed by '.'
893434 followed by ' '
This pattern should work:
#\d
foreach(var match in System.Text.RegularExpressions.RegEx.Matches(input, "#\d"))
{
Console.WriteLine(match.Value);
}
(I'm not in front of Visual Studio, but even if that doesn't compile as-is, it should be close enough to tweak into something that works).
Regex regex = new Regex("%download#(\\d+?)%", RegexOptions.SingleLine);
Matches m = regex.Matches(input);
I think will do the trick (not tested).
ReferenceURL : https://stackoverflow.com/questions/4740984/c-sharp-regex-matches-example
'programing tip' 카테고리의 다른 글
Hackintosh에서 iPhone 개발 (0) | 2021.01.07 |
---|---|
PHP 생성자의 목적 (0) | 2021.01.07 |
Font Awesome 기호 위에 배지를 추가하는 방법은 무엇입니까? (0) | 2021.01.06 |
생성자에서 암시 적 변환을 피합니다. (0) | 2021.01.06 |
목록을 복사하는 가장 좋은 방법은 무엇입니까? (0) | 2021.01.06 |