Python
 Computer >> コンピューター >  >> プログラミング >> Python

Python Regexを使用して、特定の文字列内の「1(0+)1」のすべてのパターンを検索します


このチュートリアルでは、正規表現を使用して、文字列内の1(0 + 1)のすべての出現を検出するプログラムを作成します。 。 Pythonには、正規表現を操作するのに役立つreモジュールがあります。

1つのサンプルケースを見てみましょう。

Input:
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output:
Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']

以下の手順に従って、プログラムのコードを記述します。

アルゴリズム

1. Import the re module.
2. Initialise a string.
3. Create a regex object using regular expression which matches the pattern using the re.compile(). Remember to pass a raw string to the function instead of the usual string.
4. Now, match all the occurrence of the pattern using regex object from the above step and regex_object.findall() method.
5. The above steps return a match object and print the matched patterns using match_object.group() method.

コードを見てみましょう。

# importing the re module
import re
# initializing the string
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
# creating a regex object for our patter
regex = re.compile(r"\d\(\d\+\)\d") # this regex object will find all the patter ns which are 1(0+)1
# storing all the matches patterns in a variable using regex.findall() method
result = regex.findall(string) # result is a match object
# printing the frequency of patterns
print(f"Total number of pattern maches are {len(result)}")
print()
# printing the matches from the string using result.group() method
print(result)

出力

上記のコードを実行すると、次の出力が得られます。

Total number of pattern maches are 3
['1(0+)1', '1(0+)1', '1(0+)1']

結論

チュートリアルについて疑問がある場合は、コメントセクションにその旨を記載してください。


  1. 指定された文字列のセットを使用して母音の数をカウントするPythonプログラム

    この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −文字列が与えられたので、与えられた文字列のセットを使用して母音の数を数える必要があります。 ここでは、文字列全体をトラバースして、各文字が母音であるかどうかを確認し、カウントをインクリメントします。 次に、以下の実装の概念を観察しましょう- 例 def vowel_count(str):    count = 0    #string of vowels    vowel = "aeiouAEIOU"   &nbs

  2. Pythonで特定の文字列のすべての可能な順列を見つける方法は?

    特定の文字列のすべての可能な順列を見つけるには、permutations(iterable [、r])と呼ばれる便利なメソッドを持つitertoolsモジュールを使用できます。このメソッドは、反復可能な要素の連続するrの長さの順列をタプルとして返します。 すべての順列を文字列として取得するには、関数呼び出しを繰り返し処理してタプルを結合する必要があります。例:  >>>from itertools import permutations >>>print [''.join(p) for p in permutations('