Help for Regular Expression construction

Asked

Viewed 77 times

1

Regarding the string identified below, I needed to get the ABCD value by using a regular expression, I need help to build that regular expression.

Team(\\\'ABCD\\\')

  • What language? Want to validate or extract what is in the middle of Team(...)?

2 answers

4

The regular expression would be:

\bTeam\(\\+\'([\s\S]+?)\\+\'\)

The ([\s\S]+?) is who generates group 1 and gets the result only from within the Team(\\'...'\\), already the \b at the beginning is a meta-character that identifies if it is a word, ie if you find something like TestTeam() will ignore, only separated by spaces or strings starting with Team() will "marry" the regex

If it’s Javascript:

var str = "Team(\\'ABCD\\')";
var resultados = /\bTeam\(\\+\'([\s\S]+?)\\+\'\)/g.exec(str);

console.log(resultados[1]);

var str = "Team(\\'foo bar baz\\')";
var resultados = /\bTeam\(\\+\'([\s\S]+?)\\+\'\)/g.exec(str);

console.log(resultados[1]);

If it is PHP:

$str = "Team(\\'ABCD\\')";

if (preg_match("#\bTeam\(\\\\+\'([\s\S]+?)\\\\+\'\)#", $str, $resultados)) {
    var_dump($resultados[1]);
}

If it’s Python:

import re

str = "Team(\\'ABCD\\')"
parttern = r'\bTeam\(\\+\'([\s\S]+?)\\+\'\)'

p = re.compile(parttern)
resultado = p.search(str).group(1)

print(resultado)
  • 1

    Thank you so much for the help, I used the first option and it worked!

  • 1

    @Could Marty mark the answer as correct? If you still don’t know how to do read this Faq https://pt.meta.stackoverflow.com/q/1078/3635 - Thank you!

0

You can use this expression:

[A-Z]+\b

You will get the sequence of uppercase letters ([A-Z]) right to left (+\b) until you no longer find an uppercase letter, that is, in Team(\\'ABCD\\'), will return ABCD.

View in Javascript:

var string = "Team(\\'ABCD\\')";
var result = /[A-Z]+\b/.exec(string);
console.log(result[0]);

As returns only 1 result, you use the index [0] in result[0].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.