Formatação condicional de numero de telefone Regex

Contexto: tenho um input que a medida que eu vou digitando uma funcao é chamada para verificar se o numero de telefone está no formato correto. Essa funcao deve aceitar numeros nos formatos: (XX)XXXXX-XXXX e (XX)XXXX-XXXX, e já aceita ambos os formatos!

Qual é o problema entao?: A funcao ao dar match no formato de 8 digitos não continua a correção caso o usuario digite o 9º digito.

Resumindo: quero que o regex identifique tanto o formato de 8 e 9 digitos, mas se for entrado 9 digitos, este formato que deve ser usado.

import React, {useState} from 'react'  function App(){     const [telefone, setTelefone] = useState("")      function handleTelefone(event){         const regex = /^\(?([0-9]{2})\)?([0-9]{4,5})\-?([0-9]{4})$  /mg;         var str = event.target.value;         const subst = `($  1)$  2-$  3`;          const result = str.replace(regex, subst);          setTelefone(result);     }     return(         <>             <form>                 <input type="text" value={telefone} onChange={handleTelefone.bind(this)}/>             </form>         </>     ) }  export default App

Kleene Star regex question, sed behavior?

Kleene Star with ‘sed’ is behaving as expected for me, with exception of a case where the input pattern is “ab” and the regex is “b*”. Does anyone know why this regex is not being matched against the pattern space?

This is the failure case:

$   printf "ab\n" | sed -En 's/b*// p' | od -t c 0000000   a   b  \n 0000003 

This case, without Kleene Star, behaves as expected:

$   printf "ab\n" | sed -En 's/b// p' | od -t c 0000000   a  \n 0000002 

I’m trying to match the ‘b’ and replace it with nothing.

The pattern space is ‘ab’, beginning of line is unspecified, so I’m confused why /b*/ would not match a pattern of zero or more ‘b’s, in this case ‘b’.

Oddly, this case works with the ‘.’ prepended to the ‘*’:

# fails to match $   printf "abb\n" | sed -En 's/b*// p' | od -t c 0000000   a   b   b  \n 0000004 # matches with .* ! $   printf "abb\n" | sed -En 's/b.*// p' | od -t c 0000000   a  \n 0000002 

Kleene Star matches zero or more occurrences of the preceding alphabet (in this case a single character).

By definition:

$ V^0 = \{\epsilon\}$

$ V^1 = V$

$ \forall i ( (i \gt 0) \land (V^{i + 1} = \{ wv : w \in V^i \land v \in V )\} $

Therefore $ V^0 = \{ \epsilon\}$ , $ V^1 = \{ \epsilon \cdot b\}$ , $ V^2 = \{ \epsilon \cdot b \cdot b\}$ .

$ V^* = \bigcup\limits_{i\ge0} V^i = V^0 \cup V^1 \cup …$ which I have specified by /b*/.

The following cases agree with my understanding of sed and Kleene Star:

# * : matches 0 or more occurances # no match $   printf "a\n" | sed -En 's/b*// p' | od -t c 0000000   a  \n 0000002  # match a printf "a\n" | sed -En 's/a*// p' | od -t c 0000000  \n 0000001  # match a printf "ab\n" | sed -En 's/a*// p' | od -t c 0000000   b  \n 0000002  # match aa printf "aab\n" | sed -En 's/a*// p' | od -t c 0000000   b  \n 0000002 

I tested using BSD and GNU sed, both have the same results.

Thanks!

Time complexity boost regex

How can i evaluate time complexity of matching a regex using boost?

Does it only depend on the length and the recurrency or is anything else involved?

For example, let’s assume I do have this regex that matches any alphanumeric string

[A-z0-9]+ 

and I have a function like this

isAlphanumerical(string str){   return boost::regex_match(str, "[A-z0-9]+"); } 

is there a way to tell what’s its time complexity? what about if I use add some cases like this (I also changed the former regex in order to only match combinations of numbers and capital letters ) :

[A-Z0-9]+$  |\s*$  |_*$   

so that I can also match strings only containing spaces or hypens?

And what if I also recur over the pattern like this

(?i)[A-Z0-9]+$  |\s*$  |_*$   

?

Regex para validar documento – Javascript

Estou tendo alguns problemas na hora de validar o documento.

Anteriormente eu fiz essa pergunta aqui: Regex para validar número de documento nacional

O problema que estou tendo é que o usuário está digitando números sequeciais ou iguais, por exemplo:

000000000

111111111

até

999999999

e também coisas do tipo:

1234567890

0987654321

123123123

456456456

abc123

e isso está me dando um problemão.

Bom, segue a regex que tenho:

console.log(/(?=.*\d)[A-Za-z0-9]{1,}/g.test('abc1234')); // somente números e letras ou somente números  console.log(/(?!(\d){3})\d{1,}/g.test('11111')); // numeros iguais (deveria ser false mas retorna true) // falta o regex para números sequencias e letras sequeciais que não entendi como funciona. 

Регулярное выражение для Search Regex (плагин вордпресс)

На сайте есть 5 000 тыс., публикаций в которых установлен код плеера:

[sc_embed_player_template1 fileurl="https://syte.ru/wp-content/uploads/Elvin-Grey-8-Marta.mp3" autoplay="true" loops="true"] 

Сам код плеера во всех публикациях идентичный – соответственно можно было-бы поиском убрать, а вот названия треков 5 000 тыс., раз везде разные.

Как должно выглядеть регулярное выражение, чтобы убрать выше приведенный код с разными названиями треков?

REGEX match simple pattern

I am trying to match a simple pattern using re with python but I can’t manage to reach a solution.

So I have to match a pattern like:

word.word

but not for example

word.word.word

My current REGEX is [A-Za-z]+\.[A-Za-z]+ and matches both (wrong), I tried also with ^$ to include start and end of string but does not match any of them. I am doing something wrong, I really appreciate some help. Thanks

deixar palavras do meu HTML em negrito usando regEx

basicamente, preciso selecionar todas as palavras “pattern” do meu HTML com regEx e depois substitui-las por sua versão em negrito atravém do javascript.

meu código funciona, porém, só para o primeiro elemento, por algum motivo ele não deixa os outros em negrito. (obs: esse mesmo código foi usado para deixar algumas palavras em maiúsculo, e funcionou perfeitamente em todas)

html:

<!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <meta http-equiv="X-UA-Compatible" content="ie=edge">     <title>selecionando e modificando textos com regEx</title> </head> <body>     <h1>texto</h1>      <div class="resultado">      </div>      <div class="texto">         <h1>What Is a Regular Expression?</h1>         <p> regular expression is a sequence of characters that forms a search pattern.</p>          <p>When you search for data in a text, you can use this search pattern to describe what you are searching for.</p>          <p>A regular expression can be a single character, or a more complicated pattern.</p>          <p>Regular expressions can be used to perform all types of text search and text replace operations.</p>     </div>     <script src="./regex.js"></script>  </body> </html> 

função javascript relacionada:

function patternEmNegrito() {     const regex = /pattern/ig     const texto = document.querySelector('.texto')     const resultado = texto.innerHTML.match(regex)      let textoFinal = texto.innerHTML     for(let i = 0; i < resultado.length; i++){         textoFinal = textoFinal.replace(resultado[i], `<b>$  {resultado[i]}</b>`)     }     return texto.innerHTML = textoFinal } patternEmNegrito() 

Rename multiple folders, using regex

As the title says, I’m looking for a command / tool – preferably something running from the terminal (I’m using Ubuntu on a remote server), that can replace a specific part of multiple directories at once. The folder structure is like this:

Example.of.Structure[app]  Another.Example[app]  Third.Example.of.Structure[app] 

And I want to rename all of the folders, so the [app] part gets removed from the names of the folders.

I’ve tried dabbling with basic RegEx. Matching the square brackets, and the text inside it.

Which seems to work fine, when I use it for “finding it” – but I’m really unsure how to put it into a command.

The regex I came up with, to find the text inside the brackets (including the brackets themselves) was: \[\w+\]

But how do I put this into a command?

Thanks.

Regex pattern for Any integer between -20 and 100 including -20 and 100.Numeric 3 chars max and no decimal places

Can anyone please confirm if the below regex will work for this condition

Any integer between -20 and 100 including -20 and 100.Numeric 3 chars max and no decimal places -  E.g -  -20, -18 etc..  ^((\-([1-9]|1[0-9]|20))|([0-9]|[1-8][0-9]|9[0-9]|100))$   

Find and insert tags using regex

I am converting a book from PDF to epub in calibre. But the titles are not inside header tags, hence trying a python function using regex to replace it.

example text:

<p class="calibre1"><a id="p1"></a>Chapter 370: Slamming straight on</p> <p class="softbreak"> </p> <p class="calibre1">Hearing Yan Zhaoge’s suggestion, the Jade Sea City martial practitioners here were all stunned.</p> <p class="calibre1"><a id="p7"></a>Chapter 372: Yan Zhaoge’s plan</p> <p class="softbreak"> </p> <p class="calibre1">Yan Zhaoge and Ah Hu sat on Pan-Pan’s back, black water swirling about Pan-Pan’s entire body, keeping away the seawater as he shot forward at lightning speed.</p> 

i tried using regex with

def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):      pattern = r"</a>(?i)chapter [0-9]+: [\w\s]+(.*)<br>"     list = re.findall(pattern, match.group())      for x in list:         x = "</a>(?i)chapter [0-9]+: [\w\s]+(.?)<br>"         x = s.split("</a>", 1)[0] + '</a><h2>' + s.split("a>",1)[1]         x = s.split("<br>", 1)[0] + '</h2><br>' + s.split("<br>",1)[1]     return match.group() 

and

 def replace(match, number, file_name, metadata, dictionaries, data, functions, *args, **kwargs):     pattern = r"</a>(?i)chapter [0-9]+: [\w\s]+(.*)<br>"     s.replace(re.match(pattern, s), r'<h2>$  0') 

But still not getting expected result. what i want is…

Input

</a>Chapter 370: Slamming straight on</p>

Output

</a><h2>Chapter 370: Slamming straight on</h2></p>

h2 tag is to be added in all similar instances