Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a regular expression in order to search a substring C#

I have a string which I want to examine and search for a substring within it. If the substring is found, I want to do something on the original string.

The string looks like this:

"\r\radmin@Modem -- *<456> \radmin@Modem -- *<456> "  

Goal: Search the substring pattern " -- *<456> " if it exists in the string, and return success or fail (the digits number is between 1 to infinite: 1, 5, 36, 76, 478, 975 etc.).

What is the regular expression pattern which I need?

like image 838
Orionlk Avatar asked Jun 10 '26 16:06

Orionlk


2 Answers

Use this:

var myRegex = new Regex("(?<=<)[0-9]+(?=>)");
string resultString = myRegex.Match(yourString).Value;
Console.WriteLine(resultString);
// matches 456

See the match in the Regex Demo.

Explanation

  • The lookbehind (?<=<) asserts that what precedes is <
  • [0-9]+ matches one or more digits
  • The lookahead (?=>) asserts that what follows is >
like image 84
zx81 Avatar answered Jun 12 '26 04:06

zx81


You can use this following piece of code to check if your pattern exist :

 string yourInput = "\r\radmin@Modem -- *<456> \radmin@Modem -- *<456> "  ; 
 string pattern = @"<(\d+)>"; 
 boolean success = Regex.Match(yourInput , pattern, RegexOptions.IgnoreCase).Success ; 

success will be true if a number is found.

like image 45
Perfect28 Avatar answered Jun 12 '26 06:06

Perfect28