ID:2946852
 
(See the best response by Ter13.)
Hello! I fully understand that the title may be extremely confusing, but as someone who is new to byond but not exactly newbie to coding, i need help in making this happen.

Im currently making a ttrpg here on byond, and by its nature, i am making it so dms can spawn in enemies or npcs the players to fight or interact with. I already have set in stone how everything will be coded but one of the few things i need help with is making it so inputting a strung with numbers can be detected in code. What i mean by this is using the findtext and turn2number functions

Lets say for example the dm inputed this. Inside a input: Nihil[3], renewal [1]. What im trying to do is so the find texf function can look for things like Nihil[x] inside the inputted string, and turn the nihil variable's into the number inside the [x] by using the turn2text function.

If anyone knows either a better way to do this onow what im trying to do i would highly appreciate the help!

Best response
You'll need to parse the string.

Regex allows you to define a pattern that can then be matched.

Let's set up a basic pattern:

var/regex/pattern_match = new/regex(@" *(.*?) *\[(\d+)\] *(?:,|$) *","g")


This pattern breaks down into a couple parts:

"(.*?)" is a non-greedy capture group that will capture 0 or more of any character
"(\d+)" The next capture group will capture 1 or more numeric characters in a row.

The rest of the pattern string is just structural information:

" *" means 0 or more spaces can go here
"\[(\d+)\]" specifies your brackets containing numbers.
"(?:,|$)" specifies a match for either a comma, or the end of the text.


Now that we have cooked a regex that matches the pattern you want to pull from the text, we can just use it to parse:

pattern_match.next = 1
while(pattern_match.Find(str))
var/name = pattern_match.group[1]
var/number = text2num(pattern_match.group[2])
//do something with this information


If an instance of the pattern is found, the regex datum's group list will be populated with the capture groups from our regex pattern. We can then extract the content from the capture group and use it to perform whatever work we want. In this case, we're just pulling the name as a string from group 1, and then converting group 2 to a number using text2num().

Figuring out how to locate which object you are referring to is up to you, and something you will have to determine from your code's supplied context.


You can play around with this regex pattern here. Regex101 is a great tool for prototyping and debugging regular expressions.