1679156346
Hướng dẫn Python RegEx này sẽ chỉ cho bạn 3 cách để sử dụng RegEx bên trong một hàm lambda trong Python bằng cách sử dụng các hàm filter(), map() và phương thức sort().
Có thể sử dụng RegEx bên trong hàm lambda trong Python. Bạn có thể áp dụng điều này cho bất kỳ phương thức hoặc hàm Python nào lấy một hàm làm tham số. Các hàm và phương thức như vậy bao gồm filter(), map(), any(), sort(), v.v.
Hãy tiếp tục đọc khi tôi chỉ cho bạn cách sử dụng các biểu thức chính quy bên trong hàm lambda.
Cú pháp mà hàm lambda có thể lấy RegEx làm biểu thức của nó trông như sau:
lambda x: re.method(pattern, x)
Xin lưu ý rằng bạn phải sử dụng hàm lambda trên một cái gì đó. Và đó là nơi những thứ như map(), sort(), filter(), và những thứ khác xuất hiện.
Ví dụ đầu tiên tôi sẽ chỉ cho bạn sử dụng filter()hàm:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
Trong đoạn mã trên:
Để sử dụng RegEx bên trong hàm lambda với một hàm khác như map(), cú pháp tương tự:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
Trong đoạn mã trên:
Phương pháp này re.subcho phép bạn thay thế giá trị đầu tiên bằng giá trị thứ hai. Trong ví dụ này, nó đã chuyển tất cả các lần xuất hiện của othành a.
Ví dụ cuối cùng tôi sẽ chỉ cho bạn sử dụng sort()phương pháp danh sách:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
Trong mã, hàm lambda sắp xếp danh sách dựa trên số nguyên âm. Nó thực hiện điều đó với sự kết hợp của len()phương thức, findall()phương thức của Python RegEx và mẫu [aeiou].
Từ trái cây có ít nguyên âm nhất đứng đầu. Nếu bạn sử dụng reverse=True, nó sẽ sắp xếp các loại trái cây dựa trên những loại có số lượng nguyên âm cao nhất – thứ tự giảm dần:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
Trong bài viết này, chúng tôi đã xem xét cách bạn có thể chuyển RegEx sang hàm lambda bằng cách hiển thị cho bạn các ví dụ sử dụng hàm filter(), map()và sort()phương thức.
Tôi hy vọng bài viết này cung cấp cho bạn kiến thức cần thiết để sử dụng RegEx bên trong hàm lambda.
Tiếp tục viết mã!
Nguồn: https://www.freecodecamp.org
#python #regex
1679149020
سيوضح لك هذا البرنامج التعليمي Python RegEx (التعبيرات العادية) 3 طرق لاستخدام RegEx داخل دالة lambda في Python باستخدام عامل التصفية () ووظائف الخريطة () وطريقة الفرز ().
من الممكن استخدام RegEx داخل دالة lambda في Python. يمكنك تطبيق هذا على أي طريقة أو وظيفة في Python تأخذ وظيفة كمعامل. تتضمن هذه الوظائف والأساليب عامل التصفية () والخريطة () وأي () والفرز () والمزيد.
استمر في القراءة حيث أوضح لك كيفية استخدام التعبيرات العادية داخل دالة لامدا.
الصيغة التي يمكن أن تأخذ بها دالة lambda RegEx لأن تعبيرها يبدو كما يلي:
lambda x: re.method(pattern, x)
اعلم أنه يجب عليك استخدام وظيفة lambda في شيء ما. وهنا يأتي دور أمثال map()، sort()، filter()وآخرين.
المثال الأول الذي سأوضحه لك باستخدام الوظيفة filter():
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
في الكود أعلاه:
لاستخدام RegEx داخل دالة lambda مع وظيفة أخرى مثل map()، يكون بناء الجملة مشابهًا:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
في الكود أعلاه:
تتيح لك الطريقة re.subاستبدال القيمة الأولى بالقيمة الثانية. في المثال ، حولت جميع تكرارات oإلى a.
المثال الأخير الذي سأعرضه لكم يستخدم sort()طريقة القوائم:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
في الكود ، تقوم دالة lambda بفرز القائمة بناءً على عدد أحرف العلة. يقوم بذلك باستخدام مزيج من len()الطريقة وطريقة findall()Python RegEx والنمط [aeiou].
تأتي كلمة فاكهة التي تحتوي على أقل عدد من أحرف العلة أولاً. إذا كنت تستخدم reverse=True، فإنه يرتب الثمار بناءً على تلك التي تحتوي على أكبر عدد من أحرف العلة - ترتيب تنازلي:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
في هذه المقالة ، نظرنا في كيفية تمرير RegEx إلى دالة lambda من خلال عرض أمثلة لك باستخدام الدالة filter()، map()والوظائف ، والطريقة sort().
آمل أن تعطيك هذه المقالة المعرفة التي تحتاجها لاستخدام RegEx داخل وظيفة lambda.
استمر في الترميز!
المصدر: https://www.freecodecamp.org
#python #regex
1679145360
Este tutorial Python RegEx (expressões regulares) mostrará 3 maneiras de usar RegEx dentro de uma função lambda em Python usando as funções filter(), map() e o método sort().
É possível usar RegEx dentro de uma função lambda em Python. Você pode aplicar isso a qualquer método ou função Python que receba uma função como parâmetro. Tais funções e métodos incluem filter(), map(), any(), sort() e muito mais.
Continue lendo enquanto mostro como usar expressões regulares dentro de uma função lambda.
A sintaxe com a qual uma função lambda pode receber um RegEx como sua expressão se parece com isto:
lambda x: re.method(pattern, x)
Esteja ciente de que você deve usar a função lambda em algo. E é aí que entram os gostos de map(), sort(), e outros.filter()
O primeiro exemplo que vou mostrar para você usa a filter()função:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
No código acima:
Para usar RegEx dentro de uma função lambda com outra função como map(), a sintaxe é semelhante:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
No código acima:
O re.submétodo permite substituir o primeiro valor pelo segundo. No exemplo, trocou todas as ocorrências de opara a.
O último exemplo que mostrarei usa o sort()método de listas:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
No código, a função lambda classifica a lista com base no número de vogais. Ele faz isso com a combinação do len()método, o findall()método do Python RegEx e o padrão [aeiou].
A palavra fruta com o menor número de vogais vem primeiro. Se você usar reverse=True, ele organiza as frutas com base naquelas com maior número de vogais – ordem decrescente:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
Neste artigo, vimos como você pode passar RegEx para uma função lambda mostrando exemplos usando as filter()funções map(), e o sort()método.
Espero que este artigo forneça o conhecimento necessário para usar o RegEx dentro de uma função lambda.
Continue codificando!
Fonte: https://www.freecodecamp.org
#python #regex
1679141717
이 Python RegEx(정규식) 자습서에서는 filter(), map() 함수 및 sort() 메서드를 사용하여 Python의 람다 함수 내에서 RegEx를 사용하는 3가지 방법을 보여줍니다.
Python의 람다 함수 내에서 RegEx를 사용할 수 있습니다. 함수를 매개 변수로 사용하는 모든 Python 메서드 또는 함수에 이를 적용할 수 있습니다. 이러한 함수 및 메서드에는 filter(), map(), any(), sort() 등이 포함됩니다.
람다 함수 내에서 정규식을 사용하는 방법을 보여주므로 계속 읽으십시오.
The syntax with which a lambda function can take a RegEx as its expression looks like this:
lambda x: re.method(pattern, x)
Be aware that you have to use the lambda function on something. And that’s where the likes of map(), sort(), filter(), and others come in.
The first example I will show you use the filter() function:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
In the code above:
와 같은 다른 함수가 있는 람다 함수 내에서 RegEx를 사용하려면 map()구문이 비슷합니다.
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
위의 코드에서:
이 re.sub메서드를 사용하면 첫 번째 값을 두 번째 값으로 바꿀 수 있습니다. 이 예에서는 의 모든 발생을 o로 전환했습니다 a.
내가 보여줄 마지막 예는 sort()목록 방법을 사용합니다.
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
코드에서 람다 함수는 모음 수를 기준으로 목록을 정렬합니다. len()메소드, findall()Python RegEx의 메소드 및 패턴 의 조합으로 수행합니다 [aeiou].
모음 수가 가장 적은 과일이 먼저 나옵니다. 를 사용하면 reverse=True모음이 가장 많은 과일을 기준으로 내림차순으로 배열합니다.
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
이 기사에서는 , 함수 및 메소드 를 사용하는 예제를 보여줌으로써 RegEx에서 람다 함수로 전달하는 방법을 살펴 filter()보았습니다 .map()sort()
이 기사가 람다 함수 내에서 RegEx를 사용하는 데 필요한 지식을 제공하기를 바랍니다.
계속 코딩하세요!
#python #regex
1679138100
В этом руководстве по Python RegEx (регулярные выражения) показаны 3 способа использования RegEx внутри лямбда-функции в Python с использованием функций filter(), map() и метода sort().
В Python можно использовать RegEx внутри лямбда-функции. Вы можете применить это к любому методу или функции Python, которая принимает функцию в качестве параметра. К таким функциям и методам относятся filter(), map(), any(), sort() и другие.
Продолжайте читать, пока я покажу вам, как использовать регулярные выражения внутри лямбда-функции.
Синтаксис, с помощью которого лямбда-функция может принимать RegEx в качестве своего выражения, выглядит следующим образом:
lambda x: re.method(pattern, x)
Имейте в виду, что вам нужно использовать лямбда-функцию для чего-то. И вот тут-то и появляются такие map(), как sort(), , и другие.filter()
В первом примере я покажу вам использование filter()функции:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
В приведенном выше коде:
Чтобы использовать RegEx внутри лямбда-функции с другой функцией, такой как map(), синтаксис аналогичен:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
В приведенном выше коде:
Метод re.subпозволяет заменить первое значение вторым. В примере он переключил все вхождения oна a.
В последнем примере, который я вам покажу, используется sort()метод списков:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
В коде лямбда-функция сортирует список по количеству гласных. Он делает это с помощью комбинации метода len(), findall()метода Python RegEx и шаблона [aeiou].
Первым идет слово фрукты с наименьшим количеством гласных. Если вы используете reverse=True, он упорядочивает плоды по количеству гласных в порядке убывания:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
В этой статье мы рассмотрели, как вы можете передать RegEx в лямбда-функцию, показав вам примеры с использованием функций filter(), map()и sort()метода.
Я надеюсь, что эта статья даст вам знания, необходимые для использования RegEx внутри лямбда-функции.
Продолжайте кодировать!
Источник: https://www.freecodecamp.org
#python #regex
1679134447
この Python RegEx (正規表現) チュートリアルでは、filter()、map() 関数、および sort() メソッドを使用して、Python のラムダ関数内で RegEx を使用する 3 つの方法を示します。
Python のラムダ関数内で RegEx を使用することは可能です。これは、関数をパラメーターとして受け取る任意の Python メソッドまたは関数に適用できます。このような関数とメソッドには、filter()、map()、any()、sort() などがあります。
ラムダ関数内で正規表現を使用する方法を説明するので、読み続けてください。
ラムダ関数が正規表現を式として使用できる構文は、次のようになります。
lambda x: re.method(pattern, x)
何かでラムダ関数を使用する必要があることに注意してください。そして、そこにmap()、sort()、filter()、その他が登場します。
関数を使用する最初の例を示しますfilter()。
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
上記のコードでは:
のような別の関数でラムダ関数内で RegEx を使用するにはmap()、構文は似ています。
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
上記のコードでは:
このre.subメソッドを使用すると、最初の値を 2 番目の値に置き換えることができます。この例では、出現するすべてのoを に切り替えましたa。
最後に紹介する例では、sort()リストの方法を使用しています。
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
コードでは、ラムダ関数が母音の数に基づいてリストを並べ替えます。len()メソッド、findall()Python RegEx のメソッド、および patternの組み合わせで行います[aeiou]。
母音の数が最も少ない果物が最初に来ます。を使用するとreverse=True、母音の数が最も多いものに基づいてフルーツが降順で並べられます。
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
filter()この記事では、 、 関数、map()メソッドを使用した例を示して、ラムダ関数に RegEx を渡す方法について説明しましたsort()。
この記事で、ラムダ関数内で RegEx を使用するために必要な知識が得られることを願っています。
コーディングを続けてください!
#python #regex
1679130807
Ce tutoriel Python RegEx (Regular Expressions) vous montrera 3 façons d'utiliser RegEx dans une fonction lambda en Python en utilisant les fonctions filter(), map() et la méthode sort().
Il est possible d'utiliser RegEx dans une fonction lambda en Python. Vous pouvez l'appliquer à n'importe quelle méthode ou fonction Python qui prend une fonction comme paramètre. Ces fonctions et méthodes incluent filter(), map(), any(), sort(), etc.
Continuez à lire pendant que je vous montre comment utiliser des expressions régulières dans une fonction lambda.
La syntaxe avec laquelle une fonction lambda peut prendre un RegEx comme son expression ressemble à ceci :
lambda x: re.method(pattern, x)
Sachez que vous devez utiliser la fonction lambda sur quelque chose. Et c'est là que les goûts de map(), sort(), filter(), et d'autres entrent en jeu.
Le premier exemple que je vais vous montrer utilise la filter()fonction :
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
Dans le code ci-dessus :
Pour utiliser RegEx dans une fonction lambda avec une autre fonction telle que map(), la syntaxe est similaire :
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
Dans le code ci-dessus :
La re.subméthode vous permet de remplacer la première valeur par la seconde. Dans l'exemple, il a remplacé toutes les occurrences ode a.
Le dernier exemple que je vais vous montrer utilise la sort()méthode des listes :
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
Dans le code, la fonction lambda trie la liste en fonction du nombre de voyelles. Il le fait avec la combinaison de la len()méthode, la findall()méthode de Python RegEx et le pattern [aeiou].
Le mot fruit avec le plus petit nombre de voyelles vient en premier. Si vous utilisez reverse=True, il organise les fruits en fonction de ceux qui ont le plus grand nombre de voyelles - ordre décroissant :
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
Dans cet article, nous avons examiné comment vous pouvez transmettre RegEx à une fonction lambda en vous montrant des exemples utilisant les filter()fonctions map(), et la sort()méthode .
J'espère que cet article vous donnera les connaissances dont vous avez besoin pour utiliser RegEx dans une fonction lambda.
Continuez à coder !
Source : https://www.freecodecamp.org
#python #regex
1679127180
Este tutorial de Python RegEx (Expresiones regulares) le mostrará 3 formas de usar RegEx dentro de una función lambda en Python usando las funciones filter(), map() y sort().
Es posible usar RegEx dentro de una función lambda en Python. Puede aplicar esto a cualquier método o función de Python que tome una función como parámetro. Tales funciones y métodos incluyen filter(), map(), any(), sort() y más.
Siga leyendo mientras le muestro cómo usar expresiones regulares dentro de una función lambda.
La sintaxis con la que una función lambda puede tomar un RegEx como su expresión se ve así:
lambda x: re.method(pattern, x)
Tenga en cuenta que tiene que usar la función lambda en algo. Y ahí es donde entran los gustos de map(), sort(), y otros.filter()
El primer ejemplo que te mostraré usa la filter()función:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
En el código de arriba:
Para usar RegEx dentro de una función lambda con otra función como map(), la sintaxis es similar:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
En el código de arriba:
El re.submétodo le permite reemplazar el primer valor con el segundo. En el ejemplo, cambió todas las apariciones de oa a.
El último ejemplo que les mostraré usa el sort()método de listas:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
En el código, la función lambda ordena la lista según el número de vocales. Lo hace con la combinación del len()método, el findall()método de Python RegEx y el patrón [aeiou].
La palabra fruta con el menor número de vocales va primero. Si usa reverse=True, organiza las frutas en función de las que tienen el mayor número de vocales, en orden descendente:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
En este artículo, analizamos cómo puede pasar RegEx a una función lambda mostrándole ejemplos usando las filter()funciones map(), y el sort()método.
Espero que este artículo le brinde el conocimiento que necesita para usar RegEx dentro de una función lambda.
¡Sigue codificando!
Fuente: https://www.freecodecamp.org
#python #regex
1679123539
บทช่วยสอน Python RegEx (Regular Expressions) นี้จะแสดงให้คุณเห็น 3 วิธีในการใช้ RegEx ภายในฟังก์ชัน lambda ใน Python โดยใช้ฟังก์ชัน filter(), map() และ sort()
เป็นไปได้ที่จะใช้ RegEx ภายในฟังก์ชันแลมบ์ดาใน Python คุณสามารถใช้วิธีนี้กับเมธอดหรือฟังก์ชัน Python ที่รับฟังก์ชันเป็นพารามิเตอร์ ฟังก์ชันและวิธีการดังกล่าวรวมถึง filter(), map(), any(), sort() และอื่นๆ
อ่านต่อในขณะที่ฉันแสดงวิธีใช้นิพจน์ทั่วไปภายในฟังก์ชันแลมบ์ดา
ไวยากรณ์ที่ฟังก์ชันแลมบ์ดาสามารถใช้ RegEx ได้เนื่องจากนิพจน์มีลักษณะดังนี้:
lambda x: re.method(pattern, x)
โปรดทราบว่าคุณต้องใช้ฟังก์ชันแลมบ์ดากับบางสิ่ง และนั่นคือสิ่งที่ชอบของmap(), sort(), filter(), และอื่นๆ เข้ามา
ตัวอย่างแรกที่ฉันจะแสดงให้คุณใช้filter()ฟังก์ชัน:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
ในรหัสด้านบน:
หากต้องการใช้ RegEx ภายในฟังก์ชันแลมบ์ดากับฟังก์ชันอื่น เช่นmap()ไวยากรณ์จะคล้ายกัน:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
ในรหัสด้านบน:
วิธีการ นี้re.subให้คุณแทนที่ค่าแรกด้วยค่าที่สอง ในตัวอย่าง จะสลับเหตุการณ์ทั้งหมดoเป็นa
ตัวอย่างสุดท้ายที่ฉันจะแสดงให้คุณเห็นโดยใช้sort()เมธอดของรายการ:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
ในโค้ด ฟังก์ชันแลมบ์ดาจะเรียงลำดับรายการตามจำนวนสระ มันทำด้วยการรวมกันของlen()วิธีการfindall()วิธีการของ Python RegEx และรูป[aeiou]แบบ
ผลไม้ คำที่มีจำนวนสระน้อยที่สุดมาก่อน หากคุณใช้reverse=Trueจะจัดเรียงผลไม้ตามจำนวนสระที่มีจำนวนสระมากที่สุด - เรียงลำดับจากมากไปน้อย:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
ในบทความนี้ เราได้ดูวิธีที่คุณสามารถส่งผ่าน RegEx ไปยังฟังก์ชันแลมบ์ดาโดยแสดงตัวอย่างโดยใช้filter()ฟังก์ชันmap()และsort()เมธอด
ฉันหวังว่าบทความนี้จะให้ความรู้ที่จำเป็นในการใช้ RegEx ในฟังก์ชันแลมบ์ดา
เขียนโค้ดต่อไป!
ที่มา: https://www.freecodecamp.org
#python #regex
1679119920
本 Python RegEx(正則表達式)教程將向您展示 3 種在 Python 中使用 filter()、map() 函數和 sort() 方法在 lambda 函數中使用 RegEx 的方法。
可以在 Python 的 lambda 函數中使用 RegEx。您可以將其應用於任何將函數作為參數的 Python 方法或函數。此類函數和方法包括 filter()、map()、any()、sort() 等。
繼續閱讀我向您展示的如何在 lambda 函數中使用正則表達式。
lambda 函數可以採用 RegEx 作為其表達式的語法如下所示:
lambda x: re.method(pattern, x)
請注意,您必須對某些內容使用 lambda 函數。map()這就是、sort()、filter()和其他人的用武之地。
我將向您展示的第一個示例使用該filter()函數:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
在上面的代碼中:
To use RegEx inside a lambda function with another function like map(), the syntax is similar:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
In the code above:
The re.sub method lets you replace the first value with the second one. In the example, it switched all occurrences of o to a.
我將向您展示的最後一個示例使用sort()列表方法:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
在代碼中,lambda 函數根據元音的數量對列表進行排序。它結合方法len()、findall()Python RegEx 的方法和模式來實現[aeiou]。
元音數量最少的單詞 fruit 排在最前面。如果您使用reverse=True,它會根據元音數量最多的水果排列水果 - 降序:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
filter()在本文中,我們通過向您展示使用、map()函數和方法的示例,研究瞭如何將 RegEx 傳遞給 lambda 函數sort()。
我希望本文能為您提供在 lambda 函數中使用 RegEx 所需的知識。
繼續編碼!
資料來源: https: //www.freecodecamp.org
#python #regex
1679116260
Questo tutorial Python RegEx (Regular Expressions) ti mostrerà 3 modi per usare RegEx all'interno di una funzione lambda in Python usando le funzioni filter(), map() e il metodo sort().
È possibile utilizzare RegEx all'interno di una funzione lambda in Python. Puoi applicarlo a qualsiasi metodo o funzione Python che accetta una funzione come parametro. Tali funzioni e metodi includono filter(), map(), any(), sort() e altro.
Continua a leggere mentre ti mostro come usare le espressioni regolari all'interno di una funzione lambda.
La sintassi con cui una funzione lambda può assumere una RegEx come sua espressione è la seguente:
lambda x: re.method(pattern, x)
Tieni presente che devi usare la funzione lambda su qualcosa. Ed è qui che entrano in gioco artisti del calibro di map(), sort(), filter()e altri.
Il primo esempio che ti mostrerò usa la filter()funzione:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
Nel codice sopra:
Per utilizzare RegEx all'interno di una funzione lambda con un'altra funzione come map(), la sintassi è simile:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
Nel codice sopra:
Il re.submetodo consente di sostituire il primo valore con il secondo. Nell'esempio, ha cambiato tutte le occorrenze di oin a.
L'ultimo esempio che ti mostrerò utilizza il sort()metodo delle liste:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
Nel codice, la funzione lambda ordina l'elenco in base al numero di vocali. Lo fa con la combinazione del len()metodo, il findall()metodo di Python RegEx e il pattern [aeiou].
La parola frutto con il minor numero di vocali viene prima. Se usi reverse=True, dispone i frutti in base a quelli con il maggior numero di vocali – ordine decrescente:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
In questo articolo, abbiamo esaminato come passare RegEx a una funzione lambda mostrandoti esempi utilizzando le filter()funzioni map(), e il sort()metodo.
Spero che questo articolo ti fornisca le conoscenze necessarie per utilizzare RegEx all'interno di una funzione lambda.
Continua a programmare!
Fonte: https://www.freecodecamp.org
#python #regex
1679112030
This Python RegEx (Regular Expressions) tutorial will show you 3 ways to use RegEx inside a lambda function in Python using the
filter()
,map()
functions, and thesort()
method.
It’s possible to use RegEx inside a lambda function in Python. You can apply this to any Python method or function that takes a function as a parameter. Such functions and methods include filter()
, map()
, any()
, sort()
, and more.
Keep reading as I show you how to use regular expressions inside a lambda function.
filter()
Functionmap()
Functionsort()
MethodThe syntax with which a lambda function can take a RegEx as its expression looks like this:
lambda x: re.method(pattern, x)
Be aware that you have to use the lambda function on something. And that’s where the likes of map()
, sort()
, filter()
, and others come in.
filter()
FunctionThe first example I will show you use the filter()
function:
import re
fruits = ['apple', 'mango', 'banana', 'cherry', 'apricot', 'raspberry', 'avocado']
filtered_fruits = filter(lambda fruit: re.match('^a', fruit), fruits)
# convert the new fruits to another list and print it
print(list(filtered_fruits)) # ['apple', 'apricot', 'avocado']
In the code above:
filter()
takes the lambda function as the function to execute and the fruits
list as the iterablere.match()
method of Python RegEx and uses the pattern ^a
on the argument fruit
map()
FunctionTo use RegEx inside a lambda function with another function like map()
, the syntax is similar:
import re
fruits2 = ['opple', 'bonono', 'cherry', 'dote', 'berry']
modified_fruits = map(lambda fruit: re.sub('o', 'a', fruit), fruits2)
# convert the new fruits to another list and print it
print(list(modified_fruits)) # ['apple', 'banana', 'cherry', 'date', 'berry']
In the code above:
modified_fruits
is looping through the fruits2
list with a map()
functionre.sub()
method of Python RegEx as the expression of the lambda function.The re.sub
method lets you replace the first value with the second one. In the example, it switched all occurrences of o
to a
.
sort()
MethodThe last example I will show you uses the sort()
method of lists:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)))
print(fruits) #['fig', 'banana', 'grapefruit']
In the code, the lambda function sorts the list based on the number of vowels. It does it with the combination of the len()
method, the findall()
method of Python RegEx, and the pattern [aeiou]
.
The word fruit with the lowest number of vowels comes first. If you use reverse=True
, it arranges the fruits based on those with the highest number of vowels – descending order:
import re
fruits = [ 'banana', 'fig', 'grapefruit']
# sort fruits based on the number of vowels
fruits.sort(key=lambda x: len(re.findall('[aeiou]', x)), reverse=True)
print(fruits) # ['grapefruit', 'banana', 'fig']
In this article, we looked at how you can pass in RegEx to a lambda function by showing you examples using the filter()
, map()
functions, and the sort()
method.
I hope this article gives you the knowledge you need to use RegEx inside a lambda function.
Keep coding!
Source: https://www.freecodecamp.org
#python #regex
1679068206
JavaScript regular expressions, also known as regex, are powerful tools for working with text. They allow you to search, replace, and manipulate text based on patterns.
1677769740
In questo tutorial su Python RegEx (Regular Expression), imparerai come importare espressioni regolari in Python e usarle. Utilizzo del modulo con i metodi per lavorare con le espressioni regolari in Python.
Praticamente tutti i linguaggi di programmazione là fuori supportano le espressioni regolari. Regex è integrato in linguaggi come JavaScript e Pearl, mentre altri come Java e Python hanno librerie standard per lavorarci.
In questo articolo vedremo come importare espressioni regolari in Python e utilizzarle. Vedremo anche alcuni metodi forniti da Python per lavorare con le espressioni regolari.
Python fornisce il remodulo per usare le espressioni regolari. È un modulo standard integrato in Python, quindi se hai l'ultima versione di Python, non è necessario installarlo separatamente con i gestori di pacchetti.
Per importare il remodulo in Python, lo fai con la parola chiave import:
import re
Python fornisce alcuni metodi che puoi usare per lavorare con espressioni regolari come match(), search(), findall(), split()e sub().
Per usare questi metodi con RegEx, devi farli precedere dal remodulo e dal punto ( .) in questo modo:
re.match(pattern, string) # to use the match method
re.findall(pattern, string) # to use the findall method
re.sub(pattern, string) # to use the sub method
re.search(pattern, string) # to use the search method
re.split(pattern, string) # to use the split method
Gli esempi RegEx che ho fornito utilizzeranno questi metodi.
Il match()prende un'espressione regolare e la stringa e quindi controlla se la stringa corrisponde al modello nell'espressione regolare.
Ecco un esempio:
import re
my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'
res = re.match(my_regex_1, my_txt)
print(res) # returns None
Nell'esempio sopra:
La stringa è freeCodeCamp, e lo schema è ^freecodecamp$, quindi perché il metodo match ha restituito None? È perché non trova una corrispondenza.
Ci sono alcune lettere maiuscole nella my_txtvariabile, ma il modello cerca lettere minuscole.
Se hai familiarità con RegEx in JavaScript o Pearl, puoi utilizzare il iflag per abbinare tutte le lettere maiuscole o minuscole in una stringa.
Quindi, quello che dobbiamo fare per avere una corrispondenza è usare la ibandiera. Ma usare un flag con espressioni regolari in Python è diverso da come lo usiamo in JavaScript.
Per utilizzare i flag con le espressioni regolari in Python, il remodulo fornisce le opzioni IGNORECASE, ASCII, MULTILINE, VERBOSE, DOTALLe .LOCAL
Ecco come useresti un flag con espressioni regolari in Python:
re.match(pattern, string, re.ASCII) # to perform only ASCII matching
re.findall(pattern, string, re.DOTALL) # to match any character – including a new line.
re.sub(pattern, string, re.IGNORECASE) # to perform case insensitive matching
re.search(pattern, string, re.LOCALE) # to perform case insensitive matching dependent on the current locale
re.search(pattern, string, re.VERBOSE) # to allow comments in regex
re.split(pattern, string, re.MULTILINE) # to perform multiple line matching. Commonly used with metacharacters (^ and $)
Per il nostro esempio, il flag che possiamo usare è il IGNORECASE. Usiamolo in modo da poter ottenere una corrispondenza:
import re
my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'
res = re.match(my_regex_1, my_txt, re.IGNORECASE)
print(res) #Output: <re.Match object; span=(0, 12), match='freeCodeCamp'>
Ora abbiamo una partita!
La search()funzione accetta una regex e una stringa e quindi restituisce la prima occorrenza in un oggetto match. Se non trova alcuna corrispondenza, restituisce None.
import re
my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'
my_regex = 'friday'
res = re.search(my_regex, my_txt, re.IGNORECASE)
print(res) # <re.Match object; span=(6, 12), match='Friday'>
Puoi vedere che restituisce la prima occorrenza del testo Friday, situata tra index 6e 12.
Puoi ottenere quell'indice con il start()metodo:
res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located at index ", res.start()) # The first occurrence is located at index 6
Puoi ottenere l'indice iniziale e finale dell'occorrenza in questo modo:
res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located between index", res.start(), "and index", res.end()) # The first occurrence is located between index 6 and index 12
Puoi anche usare match()con una if…elsedichiarazione:
import re
my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'
my_regex = 'friday'
if re.search(my_regex, my_txt, re.IGNORECASE):
print("Found a match!") #Output: Found a match!
else:
print("Found no match")
res = re.search(my_regex, my_txt, re.IGNORECASE)
Il findall()metodo accetta una regex e una stringa, quindi esamina la stringa e trova tutte le occorrenze che corrispondono alla regex. Mette tutte quelle occorrenze all'interno di un elenco.
Ecco un esempio:
import re
my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'
my_regex = 'friday'
res = re.findall(my_regex, my_txt, re.IGNORECASE)
print(res) # Output: ['Friday', 'Friday', 'Friday', 'Friday']
Si noti che l'espressione regolare che uso contiene il testo friday, che non corrisponde a nessuna occorrenza di "venerdì". La IGNORECASEbandiera era ciò che la faceva corrispondere a quelle occorrenze.
Il split()metodo fa ciò che implica il nome: divide una stringa in base al modello passato in essa.
Questo metodo potrebbe essere utile se vuoi filtrare alcune parole che non vuoi in una stringa.
import re
my_txt = "Python and JavaScript and C# and Java and Golang and F#"
my_regex = 'and'
res = re.split(my_regex, my_txt)
print(res) # ['Python ', ' JavaScript ', ' C# ', ' Java ', ' Golang ', ' F#']
Funziona sub()come il metodo di JavaScript replace(). Sostituisce il carattere che corrisponde all'espressione regolare che gli è stata passata.
Il sub()metodo è leggermente diverso dagli altri metodi: richiede fino a 5 parametri:
re.sub(pattern, replacement, string, count, flags)
Quindi, se vuoi specificare un flag ma non stai specificando il count, non funzionerà come previsto.
Nessuno fa una riunione in piedi il venerdì, quindi usiamo il submetodo sulla stringa che abbiamo usato per gli esempi search()e findall():
import re
my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'
my_regex = 'friday'
res = re.sub(my_regex, "Monday", my_txt, 4, re.IGNORECASE)
print(res) # Output: Every Monday, we have a standup meeting. The only reason why we might not have a meeting on a Monday is public holiday. That Monday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Monday.
Ci sono 4 occorrenze di Fridaynella my_txtstringa. Ecco perché ho specificato 4 come conteggio.
In questo articolo, abbiamo esaminato come importare espressioni regolari tramite il remodulo. Ma non ci siamo fermati qui, poiché ti ho anche illustrato come utilizzare il modulo con i metodi per lavorare con le espressioni regolari in Python.
Inoltre, abbiamo anche dato una breve occhiata a come usare i flag nelle espressioni regolari di Python.
Se trovi utile questo articolo, non esitare a condividerlo con i tuoi amici e familiari.
Fonte: https://www.freecodecamp.org
#python #regex
1677766081
在此 Python RegEx(正則表達式)教程中,您將學習如何在 Python 中導入正則表達式並使用它。將模塊與在 Python 中處理正則表達式的方法一起使用。
幾乎所有的編程語言都支持正則表達式。正則表達式內置於 JavaScript 和 Pearl 等語言中,而其他語言(如 Java 和 Python)具有使用它的標準庫。
在本文中,我們將了解如何在 Python 中導入正則表達式並使用它。我們還將了解 Python 提供的一些處理正則表達式的方法。
Python 提供了re使用正則表達式的模塊。它是 Python 內置的標準模塊,因此如果您擁有最新版本的 Python,則無需使用包管理器單獨安裝它。
要re在 Python 中導入模塊,可以使用 import 關鍵字:
import re
Python 提供了一些可用於處理正則表達式的方法,例如match(), search(), findall(),split()和sub()。
要將這些方法與 RegEx 一起使用,您必須在它們前面加上re模塊和點 ( .),如下所示:
re.match(pattern, string) # to use the match method
re.findall(pattern, string) # to use the findall method
re.sub(pattern, string) # to use the sub method
re.search(pattern, string) # to use the search method
re.split(pattern, string) # to use the split method
我提供的 RegEx 示例將使用這些方法。
接受match()正則表達式和字符串,然後檢查字符串是否與正則表達式中的模式匹配。
這是一個例子:
import re
my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'
res = re.match(my_regex_1, my_txt)
print(res) # returns None
在上面的例子中:
字符串是freeCodeCamp,模式是^freecodecamp$,那麼為什麼 match 方法返回了呢None?這是因為找不到匹配項。
變量中有一些大寫字母my_txt,但模式正在尋找小寫字母。
如果您熟悉 JavaScript 或 Pearl 中的 RegEx,則可以使用標誌i來匹配字符串中的所有大寫或小寫字母。
所以,我們需要做的就是使用i標誌來進行匹配。但是在 Python 中使用帶正則表達式的標誌與我們在 JavaScript 中的使用方式不同。
要在 Python 中使用帶有正則表達式的標誌,該re模塊提供IGNORECASE、ASCII、MULTILINE、VERBOSE、DOTALL和LOCAL選項。
這是在 Python 中使用帶正則表達式的標誌的方式:
re.match(pattern, string, re.ASCII) # to perform only ASCII matching
re.findall(pattern, string, re.DOTALL) # to match any character – including a new line.
re.sub(pattern, string, re.IGNORECASE) # to perform case insensitive matching
re.search(pattern, string, re.LOCALE) # to perform case insensitive matching dependent on the current locale
re.search(pattern, string, re.VERBOSE) # to allow comments in regex
re.split(pattern, string, re.MULTILINE) # to perform multiple line matching. Commonly used with metacharacters (^ and $)
對於我們的示例,我們可以使用的標誌是IGNORECASE. 讓我們使用它來匹配:
import re
my_txt = 'freeCodeCamp'
my_regex_1 = '^freecodecamp$'
res = re.match(my_regex_1, my_txt, re.IGNORECASE)
print(res) #Output: <re.Match object; span=(0, 12), match='freeCodeCamp'>
現在我們有比賽了!
該search()函數接受一個正則表達式和一個字符串,然後返回匹配對像中的第一個匹配項。如果找不到匹配項,則返回None.
import re
my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'
my_regex = 'friday'
res = re.search(my_regex, my_txt, re.IGNORECASE)
print(res) # <re.Match object; span=(6, 12), match='Friday'>
您可以看到它返回第一次出現的文本Friday,位於 index6和之間12。
您可以使用以下start()方法獲取該索引:
res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located at index ", res.start()) # The first occurrence is located at index 6
您可以像這樣獲取事件的開始和結束索引:
res = re.search(my_regex, my_txt, re.IGNORECASE)
print("The first occurrence is located between index", res.start(), "and index", res.end()) # The first occurrence is located between index 6 and index 12
您還可以使用match()withif…else語句:
import re
my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'
my_regex = 'friday'
if re.search(my_regex, my_txt, re.IGNORECASE):
print("Found a match!") #Output: Found a match!
else:
print("Found no match")
res = re.search(my_regex, my_txt, re.IGNORECASE)
該findall()方法接受一個正則表達式和一個字符串,然後查看字符串並找到所有與正則表達式匹配的事件。它將所有這些事件放在一個列表中。
這是一個例子:
import re
my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'
my_regex = 'friday'
res = re.findall(my_regex, my_txt, re.IGNORECASE)
print(res) # Output: ['Friday', 'Friday', 'Friday', 'Friday']
請注意我使用的正則表達式包含文本friday,它不匹配任何出現的“星期五”。該IGNORECASE標誌使它與那些事件相匹配。
該split()方法顧名思義 - 它根據傳遞給它的模式拆分字符串。
如果您想過濾掉字符串中不需要的某些單詞,此方法可能很有用。
import re
my_txt = "Python and JavaScript and C# and Java and Golang and F#"
my_regex = 'and'
res = re.split(my_regex, my_txt)
print(res) # ['Python ', ' JavaScript ', ' C# ', ' Java ', ' Golang ', ' F#']
其sub()工作原理類似於 JavaScript 的replace()方法。它替換與傳遞給它的正則表達式相匹配的字符。
該sub()方法與其他方法略有不同——它最多需要 5 個參數:
re.sub(pattern, replacement, string, count, flags)
因此,如果您想指定一個標誌但沒有指定count,它將不會按預期工作。
星期五沒有人召開站立會議,所以讓我們在用於和示例sub的字符串上使用該方法:search()findall()
import re
my_txt = 'Every Friday, we have a standup meeting. The only reason why we might not have a meeting on a Friday is public holiday. That Friday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Friday.'
my_regex = 'friday'
res = re.sub(my_regex, "Monday", my_txt, 4, re.IGNORECASE)
print(res) # Output: Every Monday, we have a standup meeting. The only reason why we might not have a meeting on a Monday is public holiday. That Monday, we talk about what we did in the previous week, and what we are going to do in the week starting from that Monday.
Friday字符串中出現 4 次my_txt。這就是為什麼我指定 4 作為計數。
在本文中,我們研究瞭如何通過re模塊導入正則表達式。但我們並沒有就此止步,因為我還向您介紹瞭如何使用該模塊以及在 Python 中處理正則表達式的方法。
此外,我們還簡要了解瞭如何在 Python 正則表達式中使用標誌。
如果您覺得這篇文章有幫助,請不要猶豫,與您的朋友和家人分享。
資料來源: https: //www.freecodecamp.org
#python #regex