1636889520
仮想エージェントまたはボットは、現在テクノロジーで最も注目されているトレンドの1つです。ボットを統合すると、ユーザーはテキストメッセージまたは会話のいずれかによってアプリをより自然に操作できるようになります。作成は簡単ではありません。機械学習と自然言語処理について何か知っている必要があります。エージェントは、プロンプトを解析して適切な応答を生成できる必要があります。正確なコンテンツを取得するには、多くの企業にはない時間とリソースが必要です。それでも、顧客はアプリの一部としてボットを期待するでしょう。どうすれば生き残り、時間とお金を費やすことができる企業と競争できますか?そこでAmazonLexが登場します。Lexは、音声とテキストの両方の対話用の会話型インターフェースを構築するためのAWSの一部であるサービスです。
Amazon Lexには、構築済みのボットを試すためのいくつかの青写真があります。作成するには、AWSコンソールにサインインし、[サービス]メニューから[ AmazonLex ]を選択します。次の画面で、青い[はじめに]ボタンをクリックします。
[ボットの作成]画面では、カスタムボットを作成したり、事前に作成されたブループリントを選択したりできます。
この画面で、BookTripサンプル(1)を選択します。名前はBookTrip
(2)のままにします。このボットは子供によって使用されないため、[いいえ]を選択します(3)。そして最後に、青い[作成]ボタン(4)をクリックします。
これにより、ボットエディターが表示されます。ここでは、コードを記述せずにボットを構成およびカスタマイズできます。ボットはバックグラウンドで構築され、数秒後、ボットとチャットできるテキスト領域が表示されます。
エディターのサンプル発話は、ボットからのプロンプトをトリガーします。ボットは、スロット内の質問に答えるようにユーザーに促します。各スロットには、名前、タイプ、およびプロンプトがあります。
この会話では、スロットがなければならないPickUpCity
のDallas
とPickUpDate
のを2020-08-02
。(このガイドは2020年8月1日に作成されました。)ユーザーが正確な日付を指定する必要はなく、代わりに人間のように言語を使用してボットと対話できることに注意してください。
スロット内のプロンプトに応答すると、確認プロンプトが表示されます。
チャットウィンドウの下に、スロットとその値が表示されていることに注意してください。
発話、スロット、確認はインテントの一部であり、ボットが完了するタスクのようなものです。ボットは複数のインテントを持つことができます。左側のサイドバーにあるBookHotelインテントをクリックします。
このインテントには4つのスロットがあります。
発話には、スロット内の名前を含めることもできます。ボットに「ホテルを予約する必要があります」と言うと、場所を尋ねられます。
ただし、「ダラスで3泊のホテルを予約する必要があります」と言うと、場所と夜のスロットが解析され、チェックイン日が尋ねられます。
各スロットの値にはタイプがあります。Lexには、一般的に使用される定義済みの型がいくつかあります。たとえば、場所はAMAZON.US_CITY
で、チェックイン日はAMAZON.DATE
です。RoomTypeスロットを見てくださいRoomTypeValue
。そのタイプはです。左側のサイドバーの[スロットタイプ]の下にある[ RoomTypeValue]をクリックします。
以来RoomTypeValue
唯一のホテルを予約するに関連する、あなたはそれ用のカスタムタイプを作成することができます。スイートなどの新しい値を追加するには、テキストボックスに「スイート」と入力し、青いプラスボタンをクリックします。次に、[スロットタイプの保存]をクリックします。変更を反映するようにプロンプトを変更し、エディターの上部にある[ビルド]ボタンをクリックしてボットを再構築する必要があります。これで、ボットが部屋タイプのプロンプトを表示するときに、スイートが選択されます。
新しいスロットと発話を追加することもできます。FirstNameの名前、AMAZON.US_FIRST_NAMEのタイプ、および「あなたの名は何ですか?」というプロンプトで新しいスロットを定義します。青いプラスアイコンをクリックして追加します。
LastName用に同様のスロットを作成します。デフォルトでは、新しいスロットは最後に追加されます。各スロットの上下のアイコンを使用して、順序を変更できます。
スロットを解析する新しい発話を作成することもできます。中括弧にスロットの名前を含めるだけです。
ボットを作成して試してみてください。
ボットはFirstNameスロットとLastNameスロットを解析し、場所の入力を求めるプロンプトを表示しました。
ボットを公開するには、エディターの上部にある青い[公開]ボタンをクリックするだけです。ボットが完成したら、モバイルアプリに接続したり、Slackなどの多くの一般的なメッセージングサービスと統合したりできます。
LexボットをSlackと統合するには、最初に新しいSlackアプリケーションを作成する必要があります。インタラクティブ機能をアクティブにする必要があります。
[基本情報]セクションでは、クライアントID、クライアントシークレット、および検証トークンが必要です。
Lexエディターで、[チャンネル]タブを選択し、サイドバーで[ Slack ]を選択します。チャンネルに名前を付け、KMSキーにaws / lexを選択します。ボットエイリアスを選択し、SlackアプリのクライアントID、クライアントシークレット、検証トークンを提供し ます。
青い[アクティブ化]ボタンをクリックして、AWS側での統合を完了します。コールバックURLに注意してください。Slackアプリを設定するためにそれらが必要になります。
Slackアプリに戻り、サイドバーから[ OAuthとアクセス許可]を選択します。LexボットのOAuthURLの値を使用して新しいリダイレクトURLを追加し、[ URLの保存]をクリックします。[スコープ]セクションで、2つの新しいスコープを追加chat:write
しteam:read
ます:と。
インタラクティブ機能とショートカットに戻り、LexボットのポストバックURLをリクエストURLに貼り付けます。画面の一番下にある緑色の[変更を保存]ボタンをクリックすることを忘れないでください。
最後のステップ:サイドバーの[イベントサブスクリプション]をクリックします。[イベントを有効にする]スイッチをオンにします。LexボットからのポストバックURLをリクエストURLに貼り付けます。[ボットイベントのサブスクライブ]セクションを展開し、message.im
イベントを追加します。画面の一番下にある緑色の[変更を保存]ボタンをクリックします。
サイドバーの[配布の管理]をクリックしてから、[ Slackに追加]ボタンをクリックします。
[許可]をクリックして承認します。
Slackで、ダイレクトメッセージでボットを検索します。
これで、Slackを介してボットとチャットできます。
ボットを作成してSlackと統合するために、どのくらいのコードを記述しましたか?なし!Lexを使用してボットを作成する場合、開発は必要ありません。そのため、技術者以外の労働者がボットを作成する可能性があります。より高度なものは、ボットをLambdaに関連付けることができます。また、アプリケーションとのより深い統合のためのRESTAPIもあります。ボットをAlexaスキルとしてデプロイすることもできます!Lexは非常に用途が広く、使いやすいです。https://docs.aws.amazon.com/lex/index.htmlのドキュメントを参照してください。誰にとっても何かがあります。読んでくれてありがとう!
リンク:https://www.pluralsight.com/guides/getting-started-with-amazon-lex
1598257276
最近 Terraform に入門した西野です。
ひととおりチュートリアルを終え、いざ自分で .tf ファイルを書く段階になった途端、default セキュリティグループのルールを抹消したい欲求がフツフツとわき起こってきました。よくあることだと思います。 *1
Output Variables) などを用いてこねくり回さないとだめなのだろうか…?と思いつつ公式ドキュメントを眺めていたところ、ちょうど良い Resource を見つけました。
default セキュリティグループをあつかうための Resource は下記の aws_default_security_group です。
Resource: aws_default_security_group)
通常の Resource の場合 Terraform は .tf ファイルにおける宣言によって対象の実体を 作成 します。
この aws_default_security_group の場合、既に存在する default セキュリティグループを 取り込む 動きをし、引数でわたされた設定で上書きするようです。
新たな VPC を作成し、当該 VPC の dafault セキュリティグループからインバウンド/アウトバウンドルールを削除してみます。
main.tf
resource "aws_vpc" "vpc" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "vpc"
}
}
resource "aws_default_security_group" "default" {
vpc_id = aws_vpc.vpc.id
}
output "default_security_group_id" {
value = aws_default_security_group.default.id
}
#aws #terraform #初心者向け #amazon vpc #小ネタ
1636889520
仮想エージェントまたはボットは、現在テクノロジーで最も注目されているトレンドの1つです。ボットを統合すると、ユーザーはテキストメッセージまたは会話のいずれかによってアプリをより自然に操作できるようになります。作成は簡単ではありません。機械学習と自然言語処理について何か知っている必要があります。エージェントは、プロンプトを解析して適切な応答を生成できる必要があります。正確なコンテンツを取得するには、多くの企業にはない時間とリソースが必要です。それでも、顧客はアプリの一部としてボットを期待するでしょう。どうすれば生き残り、時間とお金を費やすことができる企業と競争できますか?そこでAmazonLexが登場します。Lexは、音声とテキストの両方の対話用の会話型インターフェースを構築するためのAWSの一部であるサービスです。
Amazon Lexには、構築済みのボットを試すためのいくつかの青写真があります。作成するには、AWSコンソールにサインインし、[サービス]メニューから[ AmazonLex ]を選択します。次の画面で、青い[はじめに]ボタンをクリックします。
[ボットの作成]画面では、カスタムボットを作成したり、事前に作成されたブループリントを選択したりできます。
この画面で、BookTripサンプル(1)を選択します。名前はBookTrip
(2)のままにします。このボットは子供によって使用されないため、[いいえ]を選択します(3)。そして最後に、青い[作成]ボタン(4)をクリックします。
これにより、ボットエディターが表示されます。ここでは、コードを記述せずにボットを構成およびカスタマイズできます。ボットはバックグラウンドで構築され、数秒後、ボットとチャットできるテキスト領域が表示されます。
エディターのサンプル発話は、ボットからのプロンプトをトリガーします。ボットは、スロット内の質問に答えるようにユーザーに促します。各スロットには、名前、タイプ、およびプロンプトがあります。
この会話では、スロットがなければならないPickUpCity
のDallas
とPickUpDate
のを2020-08-02
。(このガイドは2020年8月1日に作成されました。)ユーザーが正確な日付を指定する必要はなく、代わりに人間のように言語を使用してボットと対話できることに注意してください。
スロット内のプロンプトに応答すると、確認プロンプトが表示されます。
チャットウィンドウの下に、スロットとその値が表示されていることに注意してください。
発話、スロット、確認はインテントの一部であり、ボットが完了するタスクのようなものです。ボットは複数のインテントを持つことができます。左側のサイドバーにあるBookHotelインテントをクリックします。
このインテントには4つのスロットがあります。
発話には、スロット内の名前を含めることもできます。ボットに「ホテルを予約する必要があります」と言うと、場所を尋ねられます。
ただし、「ダラスで3泊のホテルを予約する必要があります」と言うと、場所と夜のスロットが解析され、チェックイン日が尋ねられます。
各スロットの値にはタイプがあります。Lexには、一般的に使用される定義済みの型がいくつかあります。たとえば、場所はAMAZON.US_CITY
で、チェックイン日はAMAZON.DATE
です。RoomTypeスロットを見てくださいRoomTypeValue
。そのタイプはです。左側のサイドバーの[スロットタイプ]の下にある[ RoomTypeValue]をクリックします。
以来RoomTypeValue
唯一のホテルを予約するに関連する、あなたはそれ用のカスタムタイプを作成することができます。スイートなどの新しい値を追加するには、テキストボックスに「スイート」と入力し、青いプラスボタンをクリックします。次に、[スロットタイプの保存]をクリックします。変更を反映するようにプロンプトを変更し、エディターの上部にある[ビルド]ボタンをクリックしてボットを再構築する必要があります。これで、ボットが部屋タイプのプロンプトを表示するときに、スイートが選択されます。
新しいスロットと発話を追加することもできます。FirstNameの名前、AMAZON.US_FIRST_NAMEのタイプ、および「あなたの名は何ですか?」というプロンプトで新しいスロットを定義します。青いプラスアイコンをクリックして追加します。
LastName用に同様のスロットを作成します。デフォルトでは、新しいスロットは最後に追加されます。各スロットの上下のアイコンを使用して、順序を変更できます。
スロットを解析する新しい発話を作成することもできます。中括弧にスロットの名前を含めるだけです。
ボットを作成して試してみてください。
ボットはFirstNameスロットとLastNameスロットを解析し、場所の入力を求めるプロンプトを表示しました。
ボットを公開するには、エディターの上部にある青い[公開]ボタンをクリックするだけです。ボットが完成したら、モバイルアプリに接続したり、Slackなどの多くの一般的なメッセージングサービスと統合したりできます。
LexボットをSlackと統合するには、最初に新しいSlackアプリケーションを作成する必要があります。インタラクティブ機能をアクティブにする必要があります。
[基本情報]セクションでは、クライアントID、クライアントシークレット、および検証トークンが必要です。
Lexエディターで、[チャンネル]タブを選択し、サイドバーで[ Slack ]を選択します。チャンネルに名前を付け、KMSキーにaws / lexを選択します。ボットエイリアスを選択し、SlackアプリのクライアントID、クライアントシークレット、検証トークンを提供し ます。
青い[アクティブ化]ボタンをクリックして、AWS側での統合を完了します。コールバックURLに注意してください。Slackアプリを設定するためにそれらが必要になります。
Slackアプリに戻り、サイドバーから[ OAuthとアクセス許可]を選択します。LexボットのOAuthURLの値を使用して新しいリダイレクトURLを追加し、[ URLの保存]をクリックします。[スコープ]セクションで、2つの新しいスコープを追加chat:write
しteam:read
ます:と。
インタラクティブ機能とショートカットに戻り、LexボットのポストバックURLをリクエストURLに貼り付けます。画面の一番下にある緑色の[変更を保存]ボタンをクリックすることを忘れないでください。
最後のステップ:サイドバーの[イベントサブスクリプション]をクリックします。[イベントを有効にする]スイッチをオンにします。LexボットからのポストバックURLをリクエストURLに貼り付けます。[ボットイベントのサブスクライブ]セクションを展開し、message.im
イベントを追加します。画面の一番下にある緑色の[変更を保存]ボタンをクリックします。
サイドバーの[配布の管理]をクリックしてから、[ Slackに追加]ボタンをクリックします。
[許可]をクリックして承認します。
Slackで、ダイレクトメッセージでボットを検索します。
これで、Slackを介してボットとチャットできます。
ボットを作成してSlackと統合するために、どのくらいのコードを記述しましたか?なし!Lexを使用してボットを作成する場合、開発は必要ありません。そのため、技術者以外の労働者がボットを作成する可能性があります。より高度なものは、ボットをLambdaに関連付けることができます。また、アプリケーションとのより深い統合のためのRESTAPIもあります。ボットをAlexaスキルとしてデプロイすることもできます!Lexは非常に用途が広く、使いやすいです。https://docs.aws.amazon.com/lex/index.htmlのドキュメントを参照してください。誰にとっても何かがあります。読んでくれてありがとう!
リンク:https://www.pluralsight.com/guides/getting-started-with-amazon-lex
1598110140
みなさん、どうもたいがーです
入社してもうすぐ丸二か月が経つそうです。時間が経つのは早いですね。
AWS CLIを使うのが楽しくなってきた、今日この頃。
今やっていることも、CLIを使ってできないのかな・・・なんて考えています。
そんな今回は、AWS CLIを使ってAmazon S3を操作し、静的ウェブサイトのホスティングをやっていきたいと思います。
手順をざっくりまとめると、このような感じです。
aws s3 mb s3://[backet-name]
aws s3api put-public-access-block --bucket [backet-name] --public-access-block-configuration "BlockPublicAcls=false,IgnorePublicAcls=false,BlockPublicPolicy=false,RestrictPublicBuckets=false"
aws s3api get-public-access-block --bucket [backet-name]
{
"PublicAccessBlockConfiguration": {
"BlockPublicAcls": false,
"IgnorePublicAcls": false,
"BlockPublicPolicy": false,
"RestrictPublicBuckets": false
}
}
#初心者向け #その他 #aws cli #amazon s3
1592806597
#ElastiCacheおじさんと繋がりたい
#python #初心者向け #flask #公式チュートリアル #elasticache #developers.io
1638584040
このチュートリアルでは、JavaScriptで正規表現を使い始めるために必要なすべてを学びます。新しい式を作成する方法、それらを使用する方法、およびそれらをテストする方法を学習します。また、単純なパターンと複雑なパターンを作成する方法や、特殊な記号や文字についても学習します。
最初に明確にする必要があるのは、正規表現とは何かです。正規表現は、必要に応じてパターンまたはルールを記述する方法です。次に、文字列でこれらのパターンを使用して、それらの文字列にこれらのパターンが含まれているか、一致しているかどうかを確認できます。正規表現の良い点の1つは、多くのプログラミング言語で正規表現を使用できることです。
正規表現は、一部の機能などのように、JavaScriptの単なる別の部分ではありません。それらは基本的に小さな言語であり、他の言語から独立している言語です。もう1つの良い点は、正規表現が非常に役立つことです。彼らはあなたが非常に少ないコードで文字列で信じられないほどのことをするのを助けることができます。
悪いことは、正規表現がしばしば奇妙に見え、恐ろしいことさえあるということです。これは、より複雑なパターンに特に当てはまります。これは、多くのプログラマーがそれらについて学ぶことに本当に興奮していない理由の1つでもあります。それは間違いです。正規表現は非常に強力で、多くのコードを節約できます。このチュートリアルがこれを克服するのに役立つことを願っています。
JavaScriptで正規表現を作成したり、パターンを記述したりする場合は、2つの方法があります。
1つ目は、正規表現コンストラクターを使用する方法です。これは、RegExpオブジェクトに存在するコンストラクター関数の名前です。このコンストラクターは2つのパラメーターを受け入れます。最初のパラメーターは、記述したいパターンです。このパラメーターはオプションではありません。最後に、なぜ任意のパターンで正規表現を作成するのですか?
2番目のパラメーターは、flags
。を含む文字列です。心配しないでください、あなたはflags
すぐに学びます。このパラメーターはオプションです。フラグについて覚えておくべきことの1つは、正規表現を作成した後は、フラグを追加したり削除したりできないことです。したがって、フラグを使用する場合は、正規表現を作成するときに必ずフラグを追加してください。
// Regular expression constructor syntax
new RegExp(pattern[, flags])
// Create regular expression
// with Regular expression constructor
// without any flags
const myPattern = new RegExp('[a-z]')
// Create regular expression
// with Regular expression constructor
// with one flag
const myPattern = new RegExp('[a-z]', 'g')
正規表現を作成する2番目の方法は、正規表現リテラルを使用することです。正規表現コンストラクターと同様に、正規表現リテラルも2つの部分で構成されます。最初のものはあなたが説明したいパターンです。このパターンはスラッシュ(//
)で囲まれています。2つ目は、終了スラッシュの後に続くフラグです。フラグはオプションです。
// Regular expression literal syntax
/pattern/flags
// Create regular expression
// with regular expression literal
// without any flags
const myPattern = /[a-z]/
// Create regular expression
// with regular expression literal
// with one flag
const myPattern = /[a-z]/g
注:正規表現リテラルは、説明するパターンを囲むスラッシュを使用します。パターンの一部として1つ以上のスラッシュを追加する場合は、バックスラッシュ(\
)を使用してそれらをエスケープする必要があります\/
。
コンストラクターとリテラルは似ていますが、重要な違いが1つあります。正規表現コンストラクターは実行時にコンパイルされます。正規表現リテラルは、スクリプトがロードされるときにコンパイルされます。これは、コンストラクターは変更できるのに対し、リテラルは動的に変更できないことを意味します。
したがって、パターンをその場で変更する必要がある場合、または必要になる可能性がある場合は、リテラルではなくコンストラクターを使用して正規表現を作成します。その場でパターンを作成する場合も同じことが言えます。その場合、コンストラクターがより適切な選択です。一方、パターンを変更したり、後で作成したりする必要がない場合は、リテラルを使用してください。
パターンの作成方法に入る前に、これらのパターンの使用方法について簡単に説明しましょう。このおかげで、後でこれらのメソッドを使用して、パターンを作成するさまざまな方法をテストできるようになります。
正規表現を操作するときに使用できるメソッドがいくつかあります。最も単純なものの1つはtest()
です。このメソッドを使用するときは、テストするテキストを引数として渡します。使用する場合、このメソッドは、返すブール値を、true
文字列はあなたのパターンの一致が含まれている場合、またはfalse
それがない場合はありません。
// test() syntax
// /somePattern/.test('Some text to test')
// Passing a string
// When test() doesn't find any match
myPattern.test('There was a cat and dog in the house.')
// false
// Using a variable
// Create text for testing
const myString = 'The world of code.'
// Create pattern
const myPattern = /code/
// Test the text given a pattern
// When test() finds a match
myPattern.test(myString)
// true
使用できるもう1つの方法はexec()
です。一致するものがある場合、exec()
メソッドは配列を返します。この配列には、使用したパターン、パターンが見つかったインデックス、入力、またはテストしたテキスト、および任意のグループに関する情報が含まれています。一致するものがない場合、exec()
メソッドはを返しますnull
。
覚えておくべきことが1つあります。このexec()
メソッドは、テキストの最初の一致に関する情報のみを返します。最初の一致が見つかると停止します。複数の一致を取得したい場合は使用しないでください。
// exec() syntax
// /somePattern/.exec('Some text to test')
// Create some string for testing
const myString = 'The world of code is not full of code.'
// Describe pattern
const myPattern = /code/
// Use exec() to test the text
// When exec() finds a match
myPattern.exec(myString)
// [
// 'code',
// index: 13,
// input: 'The world of code is not full of code.',
// groups: undefined
// ]
// Describe another pattern
const myPatternTwo = /JavaScript/
// Use exec() to test the text again with new pattern
// When exec() doesn't find any match
myPatternTwo.exec(myString)
// null
test()
そしてexec()
あなたは、文字列内のパターンの一致をテストするために使用できる唯一の方法ではありません。そこにもあるsearch()
、match()
とmatchAll()
。これらのメソッドは異なり、RegExp
オブジェクトには存在しませんが、文字列に存在します。ただし、正規表現を使用できます。
これらのメソッドを使用する場合は、構文を反転する必要があります。これらのメソッドは、パターンではなく文字列で呼び出します。また、テストする文字列を引数として渡す代わりに、パターンを渡します。
最初のsearch()
、は文字列を検索し、指定されたパターンを探します。一致するものが見つかると、:matchが始まるインデックスを返します。一致するものが見つからない場合は、を返します-1
。覚えておくべきことが1つありますsearch()
。テキスト内の最初の一致のインデックスのみを返します。最初の一致が見つかると停止します。
// search() syntax
// 'Some text to test'.search(/somePattern/)
// Create some text for testing
const myString = 'The world of code is not full of code.'
// Describe pattern
const myPattern = /code/
// Use search() to search the text for the pattern
// When search() finds a match
myString.search(myPattern)
// -13
// Call search() directly on the string
// When search() doesn't find any match
'Another day in the life.'.search(myPattern)
// -1
match()
あなたは正規表現を使用することを可能にする2番目の文字列方式です。この方法は、と同様に機能しexec()
ます。一致するものが見つかった場合、match()
メソッドは、使用したパターン、パターンが見つかったインデックス、テキスト、および任意のグループに関する情報を含む配列を返します。
また、のようにexec()
、一致するものがない場合、match()
メソッドはを返しますnull
。フラグmatch()
付きのパターンを検索するために使用する場合g
、すべての一致を見つけるために、すべての一致を含む配列が返されます。
// match() syntax
// 'Some text to test'.match(/somePattern/)
// Create some text for testing
const myString = 'The world of code is not full of code.'
// Describe pattern
const myPattern = /code/
// Use match() to find any match in the ext
myString.match(myPattern)
// [
// 'code',
// index: 13,
// input: 'The world of code is not full of code.',
// groups: undefined
// ]
'Another day in the life.'.match(myPattern)
// null
// Use match() to find all matches
// Create some text for testing
const myString = 'The world of code is not full of code.'
// Describe pattern
const myPattern = /code/g // add 'g' flag
// Use match() to find any match in the ext
myString.match(myPattern)
// [ 'code', 'code' ]
と同様にmatch()
、パターンでフラグmatchAll()
を使用すると、メソッドはすべての一致を返すことができますg
。ただし、動作は異なります。このmatchAll()
メソッドはRegExp String Iterator
オブジェクトを返します。このオブジェクトからすべての一致を取得したい場合、実行できることがいくつかあります。
まず、for...of
ループを使用してオブジェクトを反復処理し、各一致を返すかログに記録できます。Array.from()
オブジェクトのコンテンツから配列を作成するために使用することもできます。または、と同じ結果を達成するスプレッド演算子を使用できますArray.from()
。
// match() syntax
// 'Some text to test'.match(/somePattern/)
// Create some text for testing
const myString = 'The world of code is not full of code.'
// Describe pattern
const myPattern = /code/g // Note we are using 'g' flag
// Use matchAll() to find any match in the ext
const matches = myString.matchAll(myPattern)
// Use for...of loop to get all matches
for (const match of matches) {
console.log(match)
}
// [
// [
// 'code',
// index: 13,
// input: 'The world of code is not full of code.',
// groups: undefined
// ],
// [
// 'code',
// index: 33,
// input: 'The world of code is not full of code.',
// groups: undefined
// ]
// ]
// Use Array.from() to get all matches
const matches = Array.from(myString.matchAll(myPattern))
// [
// [
// 'code',
// index: 13,
// input: 'The world of code is not full of code.',
// groups: undefined
// ],
// [
// 'code',
// index: 33,
// input: 'The world of code is not full of code.',
// groups: undefined
// ]
// ]
// Use spread operator to get all matches
const matches = [...myString.matchAll(myPattern)]
// [
// [
// 'code',
// index: 13,
// input: 'The world of code is not full of code.',
// groups: undefined
// ],
// [
// 'code',
// index: 33,
// input: 'The world of code is not full of code.',
// groups: undefined
// ]
// ]
正規表現の作成方法とテスト方法を知っているので、パターンの作成方法を見てみましょう。正規表現を作成する最も簡単な方法は、単純なパターンを使用することです。これは、特定のテキストを含む文字列を使用することを意味します。次に、いくつかの文字列がそのパターン(テキスト)に一致するかどうかを試すことができます。
// Create simple pattern
// with regular expression literal
const myPattern = /JavaScript/
// Test a string with the pattern
myPattern.test('One of the most popular languages is also JavaScript.')
// true
// Test a string with the pattern
myPattern.test('What happens if you combine Java with scripting?')
// false
これまでは、単純なパターンで作成された正規表現を使用してきました。これらのパターンは、いくつかの単純なケースでは十分な場合があります。ただし、より複雑なケースを扱う場合、これらの単純なパターンでは不十分です。これは、より複雑なパターンの作成を使用する必要があるときです。ここで、特別なシンボルやキャラクターが登場します。正規表現で最も頻繁に使用されるものを見てみましょう。
文字クラスは、さまざまな種類の文字へのショートカットのようなものです。たとえば、文字、数字、スペースなどの文字クラスがあります。
/* Character class - Meaning */
. - Matches any character except for newline.
\d - Matches a single digit (same as [0-9]).
\w - Matches a single alphanumeric word character in Latin alphabet, including underscore (same as [A-Za-z0-9_
\s - Matches a single white space character (space, tab, etc.) (same as [\t\r\n\v\f])
\D - Matches a single character that is not a digit (same as [^0-9])
\W - Matches a single character that is not a word character in Latin alphabet (same as [^A-Za-z0-9_])
\S - Matches a single non-white space character (same as [^\t\r\n\v\f]).
例:
// . - Matches any character except for newline
const myPattern = /./
console.log(myPattern.test(''))
// false
console.log(myPattern.test('word'))
// true
console.log(myPattern.test('9'))
// true
// \d - Matches a single digit
const myPattern = /\d/
console.log(myPattern.test('3'))
// true
console.log(myPattern.test('word'))
// false
// \w - Matches a single alphanumeric word character
const myPattern = /\w/
console.log(myPattern.test(''))
// false
console.log(myPattern.test('word'))
// true
console.log(myPattern.test('9'))
// true
// \s - Matches a single white space character
const myPattern = /\s/
console.log(myPattern.test(''))
// false
console.log(myPattern.test(' '))
// true
console.log(myPattern.test('foo'))
// false
// \D - Matches a single character that is not a digit
const myPattern = /\D/
console.log(myPattern.test('Worm'))
// true
console.log(myPattern.test('1'))
// false
// \W - Matches a single character that is not a word character
const myPattern = /\W/
console.log(myPattern.test('Worm'))
// false
console.log(myPattern.test('1'))
// false
console.log(myPattern.test('*'))
// true
console.log(myPattern.test(' '))
// true
// \S - Matches a single non-white space character
const myPattern = /\S/
console.log(myPattern.test('clap'))
// true
console.log(myPattern.test(''))
// false
console.log(myPattern.test('-'))
// true
特殊文字の別のセットはアサーションです。これらの記号を使用すると、境界などのパターン、つまり単語や行の始まりと終わりを表すことができます。アサーションを使用すると、先読み、後読み、条件式などのより高度なパターンを記述することもできます。
/* Assertion - Meaning */
^ - Matches the beginning of the string (regular expression that follows it should be at the start of the test string).
$ - Matches the end of the string (regular expression that follows it should be at the end of the test string).
\b - Matches word boundary. A match at the beginning or ending of a word.
\B - Matches a non-word boundary.
x(?=y) - Lookahead assertion. It matches "x" only if "x" is followed by "y".
x(?!y) - Negative lookahead assertion. It matches "x" only if "x" is not followed by "y".
(?<=y)x - Lookbehind assertion. It matches "x" only if "x" is preceded by "y".
(?<!y)x - Negative lookbehind assertion. It matches "x" only if "x" is not preceded by "y".
例:
// ^ - The beginning of the string
const myPattern = /^re/
console.log(myPattern.test('write'))
// false
console.log(myPattern.test('read'))
// true
console.log(myPattern.test('real'))
// true
console.log(myPattern.test('free'))
// false
// $ - The end of the string
const myPattern = /ne$/
console.log(myPattern.test('all is done'))
// true
console.log(myPattern.test('on the phone'))
// true
console.log(myPattern.test('in Rome'))
// false
console.log(myPattern.test('Buy toner'))
// false
// \b - Word boundary
const myPattern = /\bro/
console.log(myPattern.test('road'))
// true
console.log(myPattern.test('steep'))
// false
console.log(myPattern.test('umbro'))
// false
// Or
const myPattern = /\btea\b/
console.log(myPattern.test('tea'))
// true
console.log(myPattern.test('steap'))
// false
console.log(myPattern.test('tear'))
// false
// \B - Non-word boundary
const myPattern = /\Btea\B/
console.log(myPattern.test('tea'))
// false
console.log(myPattern.test('steap'))
// true
console.log(myPattern.test('tear'))
// false
// x(?=y) - Lookahead assertion
const myPattern = /doo(?=dle)/
console.log(myPattern.test('poodle'))
// false
console.log(myPattern.test('doodle'))
// true
console.log(myPattern.test('moodle'))
// false
// x(?!y) - Negative lookahead assertion
const myPattern = /gl(?!u)/
console.log(myPattern.test('glue'))
// false
console.log(myPattern.test('gleam'))
// true
// (?<=y)x - Lookbehind assertion
const myPattern = /(?<=re)a/
console.log(myPattern.test('realm'))
// true
console.log(myPattern.test('read'))
// true
console.log(myPattern.test('rest'))
// false
// (?<!y)x - Negative lookbehind assertion
const myPattern = /(?<!re)a/
console.log(myPattern.test('break'))
// false
console.log(myPattern.test('treat'))
// false
console.log(myPattern.test('take'))
// true
一致させたい文字または式の数を指定する場合は、数量詞を使用できます。
/* Quantifier - Meaning */
* - Matches the preceding expression 0 or more times.
+ - Matches the preceding expression 1 or more times.
? - Preceding expression is optional (i.e. matches 0 or 1 times).
x{n} - The "n" must be a positive integer. It matches exactly "n" occurrences of the preceding "x".
x{n, } - The "n" must be a positive integer. It matches at least "n" occurrences of the preceding "x".
x{n, m} - The "n" can be 0 or a positive integer. The "m" is a positive integer. If "m" > "n", it matches at least "n" and at most "m" occurrences of the preceding "x".
例:
// * - Matches preceding expression 0 or more times
const myPattern = /bo*k/
console.log(myPattern.test('b'))
// false
console.log(myPattern.test('bk'))
// true
console.log(myPattern.test('bok'))
// true
// + - Matches preceding expression 1 or more times
const myPattern = /\d+/
console.log(myPattern.test('word'))
// false
console.log(myPattern.test(13))
// true
// ? - Preceding expression is optional, matches 0 or 1 times
const myPattern = /foo?bar/
console.log(myPattern.test('foobar'))
// true
console.log(myPattern.test('fooobar'))
// false
// x{n} - Matches exactly "n" occurrences of the preceding "x"
const myPattern = /bo{2}m/
console.log(myPattern.test('bom'))
// false
console.log(myPattern.test('boom'))
// true
console.log(myPattern.test('booom'))
// false
// x{n, } - Matches at least "n" occurrences of the preceding "x"
const myPattern = /do{2,}r/
console.log(myPattern.test('dor'))
// false
console.log(myPattern.test('door'))
// true
console.log(myPattern.test('dooor'))
// true
// x{n, m} - Matches at least "n" and at most "m" occurrences of the preceding "x".
const myPattern = /zo{1,3}m/
console.log(myPattern.test('zom'))
// false
console.log(myPattern.test('zoom'))
// true
console.log(myPattern.test('zooom'))
// true
console.log(myPattern.test('zoooom'))
// false
グループと範囲は、グループの特殊文字またはその範囲を指定する場合に役立ちます。
/* Group or range - Meaning */
[abc] - Matches any single character in the string from characters inside the brackets.
[^abc] — Matches anything that is not inside the brackets.
[a-z] - Matches any characters in the rage from "a" to "z".
[^a-z] - Matches any characters that are not in the rage from "a" to "z".
(x) - Matches x and remembers it so we can use it later.
(?<name>x) - Creates a capturing group that can be referenced via the specified name.
(?:x) - Matches "x" but does not remember the match so the match can't be extracted from the resulting array of elements
例:
// [abc] - Matches any single character from characters inside the brackets
const myPattern = /[aei]/
console.log(myPattern.test('aei'))
// true (there is a, e, i)
console.log(myPattern.test('form'))
// false (there is not a, e or i)
// [^abc] - Matches anything that is not inside the brackets.
const myPattern = /[^aei]/
console.log(myPattern.test('aei'))
// false (there no other character than a, e and i)
console.log(myPattern.test('form'))
// true (there are other characters than a, e and i)
// [a-z] - Matches any characters in the rage from "a" to "z".
const myPattern = /[b-g]/
console.log(myPattern.test('bcd'))
// true (there are characters in range from 'b' to 'g')
console.log(myPattern.test('jklm'))
// false (there are no characters in range from 'b' to 'g')
// [^a-z] - Matches any characters that are not in the rage from "a" to "z".
const myPattern = /[^b-g]/
console.log(myPattern.test('bcd'))
// false (there are no other characters than those in range from 'b' to 'g')
console.log(myPattern.test('jklm'))
// true (there are other characters than those in range from 'b' to 'g')
// (x) - Matches x and remembers it so we can use it later.
const myPattern = /(na)da\1/
console.log(myPattern.test('nadana'))
// true - the \1 remembers and uses the 'na' match from first expression within parentheses.
console.log(myPattern.test('nada'))
// false
// (?<name>x) - Creates a capturing group that can be referenced via the specified name.
const myPattern = /(?<foo>is)/
console.log(myPattern.test('Work is created.'))
// true
console.log(myPattern.test('Just a text'))
// false
// (?:x) - Matches "x" but does not remember the match
const myPattern = /(?:war)/
console.log(myPattern.test('warsawwar'))
// true
console.log(myPattern.test('arsaw'))
// false
交互に使用すると、少なくとも複数の式に一致させることができます。
/* Alternation - Meaning */
| - Matches the expression before or after the |. Acts like a boolean OR (||).
例:
// | - Matches the expression before or after the |
const myPattern = /(black|white) swan/
console.log(myPattern.test('black swan'))
// true
console.log(myPattern.test('white swan'))
// true
console.log(myPattern.test('gray swan'))
// false
フラグは、正規表現で使用できる最後のタイプの記号です。フラグは、パターンをより強力にする簡単な方法を提供します。たとえば、フラグを使用すると、大文字と小文字の両方を無視できるため、パターンは大文字と小文字の両方に一致し、複数の一致を検索し、複数行のテキストで一致を検索できます。
/* Flag - Meaning */
g – Search globally, i.e. don't stop after the first match.
i – Ignore case, i.e. match both upper and lower case.
s - When you use it with ., . can match newline characters.
m – Multi-line input, starts with "^", ends with "$", i.e. match the beginning or end of each line.
例:
// g flag - Search globally
const myPattern = /xyz/g
console.log(myPattern.test('One xyz and one more xyz'))
// true
// i flag - Ignore case
const myPattern = /xyz/i
console.log(myPattern.test('XyZ'))
// true - the case of characters doesn't matter in case-insensitive search.
// s flag - When you use it with ., . can match newline characters
const myPattern = /foo.bar/s
console.log(myPattern.test('foo\nbar'))
// true
console.log(myPattern.test('foo bar'))
// true
console.log(myPattern.test('foobar'))
// false
正規表現は、理解や学習が難しい場合があります。ただし、これらは、少ないコードで困難で複雑な問題を解決するための非常に便利なツールになる可能性があります。これはそれだけの価値のある闘争になります。このチュートリアルが、正規表現のしくみとその使用方法を理解するのに役立つことを願っています。
この記事が気に入ったら、今後の投稿を見逃さないように購読してください。
リンク: https://blog.alexdevero.com/regular-expressions-javascript/