user1327064
user1327064

Reputation: 4337

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

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

Upvotes: 2

Views: 103

Answers (3)

Colin
Colin

Reputation: 4135

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

Upvotes: 1

Fabrizio Stellato
Fabrizio Stellato

Reputation: 1891

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]+$

Upvotes: 1

user557597
user557597

Reputation:

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

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

Output

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

Upvotes: 1

Related Questions