开发者

Check Formatting of a String

开发者 https://www.devze.com 2023-04-10 15:22 出处:网络
This has probably been answered somewhere before but since there are millions of unrelated posts about stri开发者_JAVA技巧ng formatting.

This has probably been answered somewhere before but since there are millions of unrelated posts about stri开发者_JAVA技巧ng formatting.

Take the following string:

24:Something(true;false;true)[0,1,0]

I want to be able to do two things in this case. I need to check whether or not all the following conditions are true:

  • There is only one : Achieved using Split() which I needed to use anyway to separate the two parts.
  • The integer before the : is a 1-3 digit int Simple int.parse logic
  • The () exists, and that the "Something", in this case any string less than 10 characters, is there
  • The [] exists and has at least 1 integer in it. Also, make sure the elements in the [] are integers separated by ,

How can I best do this? EDIT: I have crossed out what I've achieved so far.


A regular expression is the quickest way. Depending on the complexity it may also be the most computationally expensive.

This seems to do what you need (I'm not that good so there might be better ways to do this):

^\d{1,3}:\w{1,9}\((true|false)(;true|;false)*\)\[\d(,[\d])*\]$

Explanation

\d{1,3} 1 to 3 digits

: followed by a colon

\w{1,9} followed by a 1-9 character alpha-numeric string,

\((true|false)(;true|;false)*\) followed by parenthesis containing "true" or "false" followed by any number of ";true" or ";false",

\[\d(,[\d])*\] followed by another set of parenthesis containing a digit, followed by any number of comma+digit.

The ^ and $ at the beginning and end of the string indicate the start and end of the string which is important since we're trying to verify the entire string matches the format.

Code Sample

var input = "24:Something(true;false;true)[0,1,0]";

var regex = new System.Text.RegularExpressions.Regex(@"^\d{1,3}:.{1,9}\(.*\)\[\d(,[\d])*\]$");
bool isFormattedCorrectly = regex.IsMatch(input);

Credit @ Ian Nelson


This is one of those cases where your only sensible option is to use a Regular Expression.

My hasty attempt is something like:

var input = "24:Something(true;false;true)[0,1,0]";

var regex = new System.Text.RegularExpressions.Regex(@"^\d{1,3}:.{1,9}\(.*\)\[\d(,[\d])*\]$");

System.Diagnostics.Debug.Assert(regex.IsMatch(input));

This online RegEx tester should help refine the expression.


I think, the best way is to use regular expressions like this:

string s = "24:Something(true;false;true)[0,1,0]";
Regex pattern = new Regex(@"^\d{1,3}:[a-zA-z]{1,10}\((true|false)(;true|;false)*\)\[\d(,\d)*\]$");

if (pattern.IsMatch(s))
{
   // s is valid
}

If you want anything inside (), you can use following regex:

@"^\d{1,3}:[a-zA-z]{1,10}\([^:\(]*\)\[\d(,\d)*\]$"
0

精彩评论

暂无评论...
验证码 换一张
取 消