I'm trying to write a regex to extract a string delimited by two periods even if the first period is not present.
Example 1:
Source string: fwe4d.tobe-extracted.s4red
Output string: tobe-extracted
Example 2:
Source string: tobe-extracted.s4red
Output string: tobe-extracted
I wrote the following regex but it only works if two periods are present.
$pattern = "/\.([^\.] )\./";
CodePudding user response:
You can use a capture group and an anchor:
^(?:[^\s.] \.)?([^\s.] )\.
Explanation
^
Start of string(?:[^\s.] \.)?
Optionally match 1 non whitespace chars without a dot, and then match.
([^\s.] )
Capture group 1, match 1 non whitespace chars or a dot\.
Match the second dot