하위 문자열 특정 문자 가져 오기 이전의 모든 것
메신저에서-문자가 오는 것을 가장 좋은 방법이라고합니다. 다음은 몇 가지 가지 단순화입니다. 이전의 길이-다양하며 길이 가능
223232-1.jpg
443-2.jpg
34443553-5.jpg
그래서 0의 시작부터-바로 앞까지의 값이 필요합니다. 덜 부분은 223232, 443 및 34443553이됩니다.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("223232-1.jpg".GetUntilOrEmpty());
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
Console.WriteLine("34443553-5.jpg".GetUntilOrEmpty());
Console.ReadKey();
}
}
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
if (!String.IsNullOrWhiteSpace(text))
{
int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal);
if (charLocation > 0)
{
return text.Substring(0, charLocation);
}
}
return String.Empty;
}
}
분할 기능을 사용하십시오 .
static void Main(string[] args)
{
string s = "223232-1.jpg";
Console.WriteLine(s.Split('-')[0]);
s = "443-2.jpg";
Console.WriteLine(s.Split('-')[0]);
s = "34443553-5.jpg";
Console.WriteLine(s.Split('-')[0]);
Console.ReadKey();
}
는 a가 -
전체 숭배를 얻습니다.
String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
return str.Substring(0, index)
}
이 사건이 시작된 이후로 상황이 조금씩 움직였습니다.
이제 사용할 수 있습니다.
string.Concat(s.TakeWhile((c) => c != '-'));
이를 수행하는 한 가지 방법은 다음 String.Substring
과 함께 사용하는 것입니다 String.IndexOf
.
int index = str.IndexOf('-');
string sub;
if (index >= 0)
{
sub = str.Substring(0, index);
}
else
{
sub = ... // handle strings without the dash
}
위치 0에서 시작하여 대시를 모든 텍스트를 반환합니다.
BrainCore의 답변을 기반으로 구축 :
int index = 0;
str = "223232-1.jpg";
//Assuming we trust str isn't null
if (str.Contains('-') == "true")
{
int index = str.IndexOf('-');
}
if(index > 0) {
return str.Substring(0, index);
}
else {
return str;
}
이 목적으로 정규식을 사용할 수 있지만 입력 문자열이 정규식과 일치하지 않을 때 추가 예외를 피하는 것이 좋습니다.
먼저 정규식 패턴으로 이스케이프하는 추가 골칫거리를 피하기 위해-우리는 그 목적으로 함수를 사용할 수 있습니다.
String reStrEnding = Regex.Escape("-");
나는 이것이 아무 일도하지 않는다는 것을 알고있다. "-"가와 같기 때문에 Regex.Escape("=") == "="
, 예를 들어 character가이면 차이를 만들 것이다 @"\"
.
그런 다음 문자열 구걸에서 문자열 끝까지 일치시켜야합니다. 또는 끝이 없으면 아무 것도 일치시키지 않습니다. (빈 문자열)
Regex re = new Regex("^(.*?)" + reStrEnding);
응용 프로그램이 성능에 중요한 경우-새 Regex에 대한 별도의 줄이 아니라면 모든 것을 한 줄에 넣을 수 있습니다.
마지막으로 문자열과 일치하고 일치하는 패턴을 추출합니다.
String matched = re.Match(str).Groups[1].ToString();
그 후에는 다른 답변에서했던 것처럼 별도의 함수를 작성하거나 인라인 람다 함수를 작성할 수 있습니다. 이제 인라인 람다 함수 (기본 매개 변수를 허용하지 않음) 또는 별도의 함수 호출과 같은 두 가지 표기법을 사용하여 작성했습니다.
using System;
using System.Text.RegularExpressions;
static class Helper
{
public static string GetUntilOrEmpty(this string text, string stopAt = "-")
{
return new Regex("^(.*?)" + Regex.Escape(stopAt)).Match(text).Groups[1].Value;
}
}
class Program
{
static void Main(string[] args)
{
Regex re = new Regex("^(.*?)-");
Func<String, String> untilSlash = (s) => { return re.Match(s).Groups[1].ToString(); };
Console.WriteLine(untilSlash("223232-1.jpg"));
Console.WriteLine(untilSlash("443-2.jpg"));
Console.WriteLine(untilSlash("34443553-5.jpg"));
Console.WriteLine(untilSlash("noEnding(will result in empty string)"));
Console.WriteLine(untilSlash(""));
// Throws exception: Console.WriteLine(untilSlash(null));
Console.WriteLine("443-2.jpg".GetUntilOrEmpty());
}
}
Btw-정규식 패턴을 변경 하면 패턴이 "^(.*?)(-|$)"
나타날 때까지 "-"
또는 패턴을 찾을 수없는 경우-문자열 끝까지 모든 것을 선택할 수 있습니다.
LINQy 방식
String.Concat ( "223232-1.jpg".TakeWhile (c => c! = '-'))
(그러나 null을 테스트해야합니다.)
참고 URL : https://stackoverflow.com/questions/1857513/get-substring-everything-before-certain-char
'IT' 카테고리의 다른 글
빈 필드에 대해 SOLR을 쿼리하는 방법은 무엇입니까? (0) | 2020.08.11 |
---|---|
linq를 사용하여 ID 목록을 기반으로 여러 레코드 선택 (0) | 2020.08.11 |
jQuery는 줄 바꿈을 br로 변환 (nl2br 상당) (0) | 2020.08.11 |
여러 필드로 개체 배열을 정렬하는 방법은 무엇입니까? (0) | 2020.08.11 |
“: =”는 무엇을입니까? (0) | 2020.08.10 |