简体   繁体   中英

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

  • 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:-

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_]+[ ].*$

 ^              # 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.

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

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

...or commented (assumes RegexOptions.IgnorePatternWhitespace if you're using the format in code):

^          # 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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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