Reputation: 781
In JS, What I should do to match and put anything before >
or ~
into group one
in this regex pattern.
Pattern: (?<one>.*)(?:>|~)(?<two>.*)
https://regex101.com/r/AOY4k0/1/
Strings:
aaa
bbb>ccc
ddd~eee
In this example, aaa
should go into the <one>
group.
Upvotes: 0
Views: 122
Reputation: 163287
You could also use a character class and a negated character class starting with [^
^(?<one>[^>~\n]+)(?:[>~](?<two>.*))?$
^
Start of string(?<one>[^>~\n]+)
Group one match 1+ times any char other than >
~
or a newline(?:
Non capture group
[>~]
Match either >
or ~
(?<two>.*)
Group two match 0+ times any character except a newline)?
Close group and make it optional$
End of stringUpvotes: 1
Reputation: 18611
Use
^(?<one>.*?)(?:(?:>|~)(?<two>.*))?$
Alternative:
^(?<one>.*?)(?:[>~](?<two>.*))?$
See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?<one> group and capture to "one":
--------------------------------------------------------------------------------
.*? any character except \n (0 or more times
(matching the least amount possible))
--------------------------------------------------------------------------------
) end of "one"
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
> '>'
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
~ '~'
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
(?<two> group and capture to "two":
--------------------------------------------------------------------------------
.* any character except \n (0 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of "two"
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
Upvotes: 1