If (extract == a string character from a-z) ... type thing needed


#1

I wish to split a string and assign its contents to other strings like so

string brick = "41 red"; ... //so the result will be string concatNum = "41"; string concatText = "red";

I read in the brick string one character at a time in a state machine. Is there an easy way to ask, in my if statement, if the character is a number, a letter, or something else?

A bit like…

if (extract == a number){ \\do stuff }

or

if (extract == a,z){\\do stuff }

I know I can do the following . . .

if (extract == "0" || extract != "1" || extract != "2" || extract != "3" || extract != "4" || extract != "5" || extract != "6" || extract != "7" || extract != "8" || extract != "9" ) || { //dostuff }

Obviously this a stupidly long winded way to do something but you will get what I need to do.

I have been researching but I am getting more confused.

I have seen the terms regular expressions and Linq mentioned so I was wondering what area I need to do my homework.

If anyone could point me in the right direction it would be appreciated :slight_smile:


#2

Maybe this will help you find the right path.

http://answers.unity3d.com/questions/124160/how-to-use-the-regex-class-to-check-for-string-wit.html


#3

RegEx are incredibly powerful and would be ideal for this. If you haven’t used them before than can seem quite complicated and often looking for examples of how they are used to say mask/format post codes or telephone numbers can be a gentle approach initially.

A much longer winded way, assuming you will always have a numeric and some text separate by only one space would be to split the text by the space, then you could use isNumeric as to test for the number etc. Would be a bit messy with probably lyrics some holding variables and then moving things around in arrays or something…

Would definitely recommend @chris.claus42’s RegEx suggestion.


#4

Thanks guys.

Further study gave me .split , .IsDigit, .IsChar which all seemed appropriate and they were also suggested on the Unity forum so that’s good that I was looking in the right direction. You also suggested .isNumeric Rob which is also appropriate.

But, although I am sure they will work I think I will use Regular Expressions. I have just read a few pages of Jan Goyvaerts book called ‘Regular Expressions’ and they seem a worthy investment in time. Yes I will have to take the time to learn but they seem so powerful that I am sure I will use them again in the future.

Thanks for your help guys.


#5

I think you hit the nail on the head there @Paul_Land, it’s one of those things that will need a bit of investment of time, but once you get the hang of them and, if you are lucky(?) enough to use them regularly (excuse the pun!), they will indeed be useful over and over again.

Good shout @chris.claus42 :slight_smile: