This is not a duplicate because all the other questions were not in AS3.
Here is my problem: I am trying to find some substrings that are in the "storage" string, that are in another string. I need to do this because my game server is sending the client random messages that contain on of the strings in the "storage" string. The strings sent from the server will always begin with: "AA_".
My code:
private var storage:String = AA_word1:AA_word2:AA_word3:AA_example1:AA_example2";
if(test.indexOf("AA_") >= 0) {
//i dont even know if this is right...
}
}
If there is a better way to do this, please let me know!
Why not just using String.split() :
var storage:String = 'AA_word1:AA_word2:AA_word3:AA_example1:AA_example2';
var a:Array = storage.split('AA_');
// gives : ,word1:,word2:,word3:,example1:,example2
// remove the 1st ","
a.shift();
trace(a); // gives : word1:,word2:,word3:,example1:,example2
Hope that can help.
Regular Expressions are the right tool for this job:
function splitStorage(storage: String){
var re: RegExp = /AA_([\w]+):?/gi;
// Execute the regexp until it
// stops returning results.
var strings = [];
var result: String;
while(result = re.exec(storage)){
strings.push(result[1]);
}
return strings;
}
The important part of this is the regular expression itself: /AA_([\w]+):?/gi
This says find a match starting with AA_, followed by one-or-more alphanumeric characters (which we capture) ([\w]+), optionally followed by a colon.
The match is then made global and case insensitive with /gi.
If you need to capture more than just letters and numbers - like this: "AA_word1 has spaces and [special-characters]:" - then add those characters to the character set inside the capture group.
e.g. ([-,.\[\]\s\w]+) will also match hyphen, comma, full-stop, square brackets, whitespace and alphanumeric characters.
Also you could do it with just one line, with a more advanced regular expression:
var storage:String = 'AA_word1:AA_word2:AA_word3:AA_example1:AA_example2';
const a:Array = storage.match(/(?<=AA_)\w+(?=:|$)/g);
so this means: one or more word char, preceeded by "AA_" and followed by ":" or the end of string. (note that "AA_" and ":" won't be included into the resulting match)
Related
How do i check for the word "Hello" inside a string in an if statement but it should only detect if the word "Hello" is alone and not like "Helloo" or "HHello"
The easiest way to do such thing is to use regular expressions. By using regular expressions you can define a rule in order to validate a specific pattern.
Here is the rule for the pattern you required to be matched:
The word must contain the string "hello"
The string "hello" must be preceded by white-space, otherwise it must be the found at the beginning of the string to be matched.
The string "hello" must be followed by either a '.' or a white-space, Otherwise it must be found at the end of the string to be matched.
Here is a simple js code which implements the above rule:
let string = 'Hello, I am hello. Say me hello.';
const pattern = /(^|\s)hello(\s|.|$)/gi;
/*const pattern = /\bhello\b/ you can use this pattern, its easier*/
let matchResult = string.match(pattern);
console.log(matchResult);
In the above code I assumed that the pattern is not case sensitive. That is why I added case insensitive modifier ("i") after the pattern. I also added the global modifier ("g") to match all occurrence of the string "hello".
You can change the rule to whatever you want and update the regular expression to confirm to the new rule. For example you can allow for the string to be followed by "!". You can do that by simply adding "|!" after "$".
If you are new to regular expressions I suggest you to visit W3Schools reference:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
One way to achieve this is by first replacing all the non alphabetic characters from string like hello, how are you #NatiG's answer will fail at this point, because the word hello is present with a leading , but no empty space. once all the special characters are removed you can simply split the string to array of words and filter 'hello' from there.
let text = "hello how are you doing today? Helloo HHello";
// Remove all non alphabetical charachters
text = text.replace(/[^a-zA-Z0-9 ]/g, '')
// Break the text string to words
const myArray = text.split(" ");
const found = myArray.filter((word) => word.toLowerCase() == 'hello')
// to check the array of found ```hellos```
console.log(found)
//Get the found status
if(found.length > 0) {
console.log('Found')
}
Result
['hello']
Found
Quick question
If I am making a command like the following
!add {gamename}{gamedescription}{gamestatus}
How would I know that each argument is inside of the {}
I know the actual command is my first arg
let args = message.content.substring(PREFIX.length).split(" ");
switch(args[0]) {
case 'status':
PREFIX being the '!'
Just not sure how I set argument 1 has the first string inside of the first {} and so on.
This regular expression will do the trick. Test it out below.
const regex = /{(.+?)}/g;
const string = '!add {game}{game description}{game status}';
const args = [];
let match;
while (match = regex.exec(string)) args.push(match[1]);
console.log(args);
Explanation:
To see how the regex works and what each character does, check it out here. About the while loop, it iterates through each match from the regex and pushes the string from the first capturing group into the arguments array.
Small, but worthy note:
. does not match line breaks, so arguments split up into multiple lines within a message will not be included. To prevent this, you could replace any new line character with a space before using the regex.
You can use a regular expression to capture substrings in a pattern.
const message = {
content: '!add {gamename}{gamedescription}{gamestatus}'
};
const matches = message.content.match(/^!([a-zA-Z]+) {([a-zA-Z]+)}{([a-zA-Z]+)}{([a-zA-Z]+)}/);
if (matches) {
console.log(matches[1]); // add
console.log(matches[2]); // gamename
console.log(matches[3]); // gamedescription
console.log(matches[4]); // gamestatus
}
When the string matches the pattern, the matches object has substrings surrounded by () in matches[1], matches[2], matches[3] and matches[4]. matches[0] has the entire matched string (!add {gamename}{gamedescription}{gamestatus} in this case).
I have a large set of JavaScript snippets each containing a line like:
function('some string without numbers', '123,71')
and I'm hoping to get a regex together to pull the numbers from the second argument. The second argument can contain an arbitrary number of comma separated numbers (inlcuding zero numbers), so the following are all valid:
''
'2'
'17,888'
'55,1,6000'
...
The regex '(?:\d+|,)*' successfully matches the quoted numbers, but I have no idea how to match each of the numbers. Placing a capture group around the \d+ seems to capture the last number (if there is one present -- it doesn't work if the second argument is just ''), but none of the others.
In your case, you may match and capture the digits inside the single quotes and then split them with a comma:
var s = "function('some string without numbers', '123,71')";
var res = s.match(/'([\d,]+)'/) || ["", ""];
console.log(res[1].split(','));
The /'([\d,]+)'/ regex will match a ', then 1+ digits or commas (placing that value into Group 1) and then a closing '.
If you want to run the regex globally, use
var s = "function('some string without numbers', '123,71')\nfunction('some string without numbers', '13,4,0')";
var rx = /'([\d,]+)'/g;
var res = [], m;
while ((m=rx.exec(s)) !== null) {
res.push(m[1].split(','));
}
console.log(res);
If you have a numbers in a variable x like this:
var x = '55,1,6000';
then use this to have the list of numbers:
var array = x.split(',');
If you can have some whitespace before/after the comma then use:
var array = x.split('\s*,\s*');
or something like that.
Sometimes it is easier to match the thing that you don't want and split on that.
I have the input as
var = primarynode.domain.local
and now I Need only primarynode from it.
I was looking both split and tokenize but not able to do it in one line code. does anyone know how to do it in one line code?
Well assuming that you want to just get the first word(before . )
from the input string.
You can use the tokenize operator of the String
If you have
def var = "primarynode.domain.local"
then you can do
def firstValue = var.tokenize(".")[0]
println firstValue
output
primarynode
The split method works, you just have to be aware that the argument is a regular expression and not a plain String. And since "." means "any character" in a regular expression, you'll need to escape it...
var = 'primarynode.domain.local'.split(/\./)[0]
...or use a character class (the "." is not special inside a character class)
var = 'primarynode.domain.local'.split(/[.]/)[0]
In ActionScript3 i wanted to get the text between 2 quotes from some HTML using a input index value where i would simply increase the 2nd quote characters value by 1. This would be very simple however i have now noticed using indexOf does not seem to work correctly with quotes and other special characters.
So my question is if you have some HTML style text like this:
var MyText:String = '<div style="text-align:center;line-height:150%"><a href="http://www.website.com/page.htm">';
How can i correctly get the index of a quote " or other special character?
Currently i try this:
MyText.indexOf('"',1)
but after 0 it always returns the wrong index value.
Also a quick additional question would be is there a better way than using ' ' to store strings with characters like " inside? So if i had other ' characters etc it won't cause problems.
Edit -
This is the function i had created (usage = GetQuote(MyText,0) etc)
// GetQuote Function (Gets the content between quotes at a set index value)
function GetQuote(Input:String, Index:Number):String {
return String(Input.substr(Input.indexOf('"', Index), Input.indexOf('"', Index + 1)));
}
The return for GetQuote(MyText,0) is "text-align yet i need text-align:center;line-height:150% instead.
First off, index of the first quote is 11 and both MyString.indexOf('"') and MyString.indexOf('"',1) return the right value (the latter also works because you don't actually have a quote at the beginning of your string).
When you need to use an single quote inside another one or a double quote inside another one you need to escape the inner one(s) using backslashes. So to catch a single quote you would use it like '\''
There are several ways of stripping a value from a string. You can use the RegExp class or use standard String functions like indexOf, substr etc.
Now what exactly would you like the result to become? Your question is not obvious.
EDIT:
Using the RegExp class is much easier:
var myText:String = '<div style="text-align:center;line-height:150%"><a href="http://www.website.com/page.htm">';
function getQuote(input:String, index:int=0):String {
// I declared the default index as the first one
var matches:Array = [];
// create an array for the matched results
var rx:RegExp = /"(\\"|[^"])*"/g;
// create a RegExp rule to catch all grouped chars
// rule also includes escaped quotes
input.replace(rx,function(a:*) {
// if it's "etc." we want etc. only so...
matches.push(a.substr(1,a.length-2));
});
// above method does not replace anything actually.
// it just cycles in the input value and pushes
// captured values into the matches array.
return (index >= matches.length || index < 0) ? '' : matches[index];
}
trace('Index 0 -->',getQuote(myText))
trace('Index 1 -->',getQuote(myText,1))
trace('Index 2 -->',getQuote(myText,2))
trace('Index -1 -->',getQuote(myText,-1))
Outputs:
Index 0 --> text-align:center;line-height:150%
Index 1 --> http://www.website.com/page.htm
Index 2 -->
Index -1 -->