我需要将“=”符号后面的任何文本匹配到未注释掉的行的行尾。你能建议一个适用于此的正则表达式吗?
Example:
// Username = admin
Username = [any text here should match regex]
// Password = password
Password= [any text here should match regex]
更新了以下示例:
One more example just for clarification:
// FilePath = //test/test/test.log
FilePath= //test/test/test.log
“=”之前的任何内容都是单词或单词组。其他任何事情都可以/将被忽略。
单词和“=”之间是否有空格无关紧要。我还没有能够实现“或”子句,但这是我正在努力工作的当前正则表达式。如果你有一个更好的解决方案或者可以帮助更新我的正则表达式来工作即时游戏:
Different permutations:
(?<=Username=).+
(?<=Username =).+
(?<=Password=).+
(?<=Password =).+
解决: 感谢您提供所有示例和快速回复/帮助。以下两个正则表达式最适合我的情况,具体取决于我是否希望“=”之后的所有匹配或“=”之后的单个匹配基于“=”之前的特定单词。
^\s*\w+\s*=\s*(.+)$ // Returns all matches
^\s*Username\s*=\s*(.+)$ // Returns a single match for a specific field
答案 0 :(得分:3)
这应该有效:
^\s*\w+\s*=\s*(.+)$
以下是使用此正则表达式的示例:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string line = " Username = [any text here should match regex]";
Regex r = new Regex(@"^\s*\w+\s*=\s*(?<text>.+)$");
Match m = r.Match(line);
if (m.Success)
Console.WriteLine(r.Match(line).Result("${text}"));
}
}
答案 1 :(得分:1)
这应该是诀窍:
^\s*(?!//)\w+\s*=\s*(.*)
它说的是:
^
行的开头
\s*
任意数量的空格
(?!//)
暂无评论
\w+
至少一个单词字符(如果变量名中允许使用其他字符,则应该扩展)
\s*
任意数量的空格
=
egal sign
(.*)
该行的其余部分(在一个组中,因此您可以提取该值)
答案 2 :(得分:0)
答案 3 :(得分:0)
^[^/]*=(.*)$
文本将匹配到反向引用\ 1.
如果找到单个/,则会失败。
答案 4 :(得分:0)
我可以使用以下内容(我正在使用$
匹配换行符选项):
Section\:(?:[^\:]*(?:=.*)?\n)*\s*Field\s*=\s*(.*?)\s*$
Section
是部分标识符Field
是字段标识符您可以使用以下内容在regexpal上对此进行测试:
AnotherSection:
SomeField = x
AnotherField = y
Section:
SomeField = Z
AnotherField = Q
TricksyBlankField
Field
// ^ this field is blank
// Field = ignored because I'm a comment
Herp = : <-- literal colon
Field = (everything in the parentheses get captured)
ExtraStuff = something
RegexPal不显示组匹配,但它就在那里。