Skip to content

Instantly share code, notes, and snippets.

@tonmcg
Last active December 17, 2018 13:29
Show Gist options
  • Save tonmcg/8d63177f6b23947ed21d5941464fb7d1 to your computer and use it in GitHub Desktop.
Save tonmcg/8d63177f6b23947ed21d5941464fb7d1 to your computer and use it in GitHub Desktop.
M Language Text Functions
let
Text.IsAlphaNumeric = (string as text) =>
let
// ASCII representation of numbers 0-9 and letters a-z and A-Z only
// analogous to the regex "^[a-zA-Z0-9]*$"
ASCIIList = List.Transform({48..57,65..90,97..122}, each Character.FromNumber(_)),
textLength = Text.Length(string),
isAlphaNumeric = // does the string contain only numbers and letters
List.Generate(
()=>
[
n = 0,
nthCharacter = Text.At(string,n),
coerceToNumber = try Number.ToText(nthCharacter) otherwise nthCharacter,
result = List.Contains(ASCIIList,coerceToNumber)
], // initial
each [n] < textLength, // condition
each
[
n = [n] + 1,
nthCharacter = Text.At(string,n),
coerceToNumber = try Number.ToText(nthCharacter) otherwise nthCharacter,
result = List.Contains(ASCIIList,coerceToNumber)
], // next
each [result] // selector
),
isValid = not List.Contains(isAlphaNumeric, false)
in
isValid,
DefineDocs = [
Documentation.Name = " Text.IsAlphaNumeric",
Documentation.Description = " Tests a string for alphanumeric characters and values only.",
Documentation.LongDescription = " Tests a string for alphanumeric characters and values only. Returns TRUE if the supplied string contains numbers 0-9 and uppercase or lowercase letters only. Returns FALSE otherwise.",
Documentation.Category = " Text.Information",
Documentation.Source = " ",
Documentation.Author = " Tony McGovern, emdata.ai",
Documentation.Examples = {
[
Description = "Test the string ""AlbrechtMayer1stOboeBerlinerPhilharmoniker"" for the existence of only numbers and letters.",
Code = " IsAlphaNumeric(""AlbrechtMayer1stOboeBerlinerPhilharmoniker"")",
Result = " TRUE"
]
}
]
in
Value.ReplaceType(
Text.IsAlphaNumeric,
Value.ReplaceMetadata(
Value.Type(Text.IsAlphaNumeric),
DefineDocs
)
)
@DNC1971
Copy link

DNC1971 commented May 31, 2018

Thanks, Tony this is useful. What would make this really useful in my case would be if this was capable of extracting the numbers only from an AlphaNumeric string. It looks like it would be possible to do it with some alterations to this code. Unfortunately, my M skills are not good enough for that. Is this something that you could look at, please.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment