I am using python.
The pattern is:
JavaScript
x
2
1
re.compile(r'^(.+?)-?.*?(.+?)')
2
The text like:
JavaScript
1
4
1
text1 = 'TVTP-S2(xxxx123123)'
2
3
text2 = 'TVTP(xxxx123123)'
4
I expect to get TVTP
Advertisement
Answer
Another option to match those formats is:
JavaScript
1
2
1
^([^-()]+)(?:-[^()]*)?([^()]*)
2
Explanation
^
Start of string([^-()]+)
Capture group 1, match 1+ times any character other than-
(
and)
(?:-[^()]*)?
As the-
is excluded from the first part, optionally match-
followed by any char other than(
and)
([^()]*)
Match from(
till)
without matching any parenthesis between them
Example
JavaScript
1
8
1
import re
2
3
regex = r"^([^-()]+)(?:-[^()]*)?([^()]*)"
4
s = ("TVTP-S2(xxxx123123)n"
5
"TVTP(xxxx123123)n")
6
7
print(re.findall(regex, s, re.MULTILINE))
8
Output
JavaScript
1
2
1
['TVTP', 'TVTP']
2