[英]Parse a value from a string
我在谷歌上搜索了30分钟,但没有找到任何可以帮助我的东西。
我的问题是我正在尝试使用RegExp解析字符串中的某些内容。 我通常是PHP开发人员,将为此使用preg_match_all()
,但是由于C#中不存在此功能(确实如此),所以我还需要其他功能。
想象一下我有这个字符串:
string test = "Hello this is a 'test' a cool test!";
现在,我想获取单引号( ' )内的内容-在此示例测试中 。
在此先感谢您的帮助。 对不起,我的英语不好,这不是我的母语! :/
C#进行preg_match_all
是使用System.Text.RegularExpressions.Regex
类,然后使用Match
方法。
一种更简单的非正则表达式方式:
string textInQuotes = String.Empty;
string[] split = test.Split('\'');
if (split.Length > 2) textInQuotes = split[1];
这是示例应用程序代码。
using System;
using System.Text.RegularExpressions;
namespace ExampleApp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// This is your input string.
string test = "Hello this is a 'test' a cool test!";
// This is your RegEx pattern.
string pattern = "(?<=').*?(?=')";
// Get regex match object. You can also experiment with RegEx options.
Match match = Regex.Match(test, pattern);
// Print match value to console.
Console.WriteLine(match.Value);
}
}
}
希望它帮助!
这是一个正则表达式解决方案,允许在文本的引号部分加上转义的定界符。 如果您更喜欢* nix反斜杠样式的转义符,只需用(\\\\')
替换正则表达式('')
的相应部分。
static readonly Regex rxQuotedStringLiteralPattern = new Regex(@"
# A quoted string consists of
' # * a lead-in delimiter, followed by
(?<content> # * a named capturing group representing the quoted content
( # which consists of either
[^'] # * an ordinary, non-delimiter character
| # OR
('') # * an escape sequence representing an embedded delimiter
)* # repeated zero or more times.
) # The quoted content is followed by
' # * the lead-out delimiter
"
, RegexOptions.ExplicitCapture|RegexOptions.IgnorePatternWhitespace
) ;
public static IEnumerable<string> ParseQuotedLiteralsFromStringUsingRegularExpressions( string s )
{
for ( Match m = rxQuotedStringLiteralPattern.Match( s ?? "" ) ; m.Success ; m = m.NextMatch() )
{
string raw = m.Groups[ "content" ].Value ;
string cooked = raw.Replace( "''" , "'" ) ;
yield return cooked ;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.