简体   繁体   English

如何匹配正则表达式中包含^的字符串?

[英]How to match string that contains ^ in regular expression?

I tried to make a regular expression using online tool but not succeeded. 我尝试使用在线工具进行正则表达式,但没有成功。 Here is the string i need to match:- 这是我需要匹配的字符串:

27R4FF^27R4FF Text until end 27R4FF ^ 27R4FF文本直到结尾

  • always starts with alphanumeric (case-insensitive) 始终以字母数字开头(不区分大小写)
  • then always caret sign ^ (no space before & after) 然后总是插入符号^(前后没有空格)
  • then alphanumeric string 然后是字母数字字符串
  • then always one white space 然后总是一个空格
  • then string until end. 然后字符串直到结束。

Here is the regular expression that is not working for me:- 这是不适合我的正则表达式:-

((?:[a-z][a-z]*[0-9]+[a-z0-9]*))(\^)((?:[a-z][a-z]*[0-9]+[a-z0-9]*)).*?((?:[a-z][a-z]+))

c# code:- C#代码:-

string txt = "784SFS^784SFS Value is here";

var regs = @"((?:[a-z][a-z]*[0-9]+[a-z0-9]*))(\^)((?:[a-z][a-z]*[0-9]+[a-z0-9]*)).*?((?:[a-z][a-z]+))";
Regex r = new Regex(regs, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(txt);
Console.Write(m.Success ? "matched" : "didn't match");
Console.ReadLine();

Help appreciated. 帮助表示赞赏。 Thanks 谢谢

Verbatim ^[^\\W_]+\\^[^\\W_]+[ ].*$ 逐字^[^\\W_]+\\^[^\\W_]+[ ].*$

 ^              # BOS
 [^\W_]+        # Alphanum
 \^             # Caret
 [^\W_]+        # Alphanum
 [ ]            # Space
 .*             # Anything
 $              # EOS

Output 产量

 **  Grp 0 -  ( pos 0 , len 28 ) 
27R4FF^27R4FF Text until end  

I didn't get if string 'until the end' should be matched. 如果字符串'until the end'应该匹配,我没有得到。

This works for 这适用于

27R4FF^27R4FF Text

^\w+\^\w+\s\w+$

if you have some spaces at the end, try with 如果结尾有空格,请尝试

^\w+\^\w+\s[\w\s]+$

Try this: https://regex101.com/r/hD0hV0/2 试试这个: https : //regex101.com/r/hD0hV0/2

^[\da-z]+\^[\da-z]+\s.*$

...or commented (assumes RegexOptions.IgnorePatternWhitespace if you're using the format in code): ...或已注释(如果您在代码中使用格式,则假定RegexOptions.IgnorePatternWhitespace):

^          # always starts...
[\da-z]+   # ...with alphanumeric (case-insensitive)
\^         # then always caret sign ^ (no space before & after)
[\da-z]+   # then alphanumeric string
\s         # then always one white space
.*         # then string...
$          # ...until end.

The other answers don't actually match what you describe (at the time of this writing) because \\w matches underscore and you didn't mention any limitations on "the string at the end". 其他答案与您描述的内容实际上不符(在撰写本文时),因为\\ w与下划线匹配,并且您未提及“末尾的字符串”的任何限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM