Help needed with regular expressions

2 visualizzazioni (ultimi 30 giorni)
Axel Teboul
Axel Teboul il 10 Lug 2022
Risposto: Stephen23 il 10 Lug 2022
Hello can someone help me break down this combination of regular expression by separating and expalining each regular expression?
One of my problem is I'm not sure where each regular expression starts and ends, expecially concerning the backlslashes; for example which one a a singular expression: \-{0,1}, -{0,1}, or {0,1} or even {0,1}\?

Risposte (2)

DGM
DGM il 10 Lug 2022
Modificato: DGM il 10 Lug 2022
I'm sure someone can be more precise with this explanation, but here goes:
[G] any one of the characters within the square brackets (there's only one character)
\-{0,1} a literal minus sign, either 0 or 1 times
\d{1,} any digit, at least once
\.* a literal period, zero or more times
\d* any digit, zero or more times
tline = 'akldjflkGjsdfkG-9kl4G-444.444kj4';
regexp(tline,'[G]\-{0,1}\d{1,}\.*\d*','match')
ans = 1×2 cell array
{'G-9'} {'G-444.444'}
can be simplified:
regexp(tline,'G\-?\d+\.*\d*','match')
ans = 1×2 cell array
{'G-9'} {'G-444.444'}
Of course, If we're trying to simplify, it would also probably make sense to avoid performing the same regexp() call twice.

Stephen23
Stephen23 il 10 Lug 2022
Do not learn from this regular expression.
% [G]\-{0,1}\d{1,}\.*\d*
% ^^^ match literal 'G' once, square brackets are superfluous
% ^^^^^^^ match optional literal '-', backslash is superfluous
% ^^^^^^ match one or more digit characters
% ^^^ match zero or more literal period/dot character
% ^^^ match zero or more digit characters
My guess is that this expression supposed to match numbers with optional leading negative sign and optional fractional digits, but why the author wanted to match an infinite number of decimal points is unclear. Note that you can replace all of the curly-brace quantifiers with simpler single-character quantifiers e.g. ? or + or *. Recommended:
G-?\d+\.?\d*
G[-+]?\d+\.?\d*
Rather than calling REGEXP twice with exactly the same inputs, it would be more efficient to call it once.

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Prodotti


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by