Hamun8
Hamun8

Reputation: 11

Regex: need some help match using semicolon

I have the following input: Mobileapp/1.19.2 (SM-S908B; Android 12; da-DK)

I either need to match (SM-S908B; and da-DK) or just (SM-S908B;

So match anything between ( and first ; and last ; and )

I tried and and was able to use this expression ([^(;]+);([^;]+) But it matches to SM-S908B; Android 12

Would really appreciate if anyone could help since I am still learning Regex.

Upvotes: 1

Views: 42

Answers (1)

JvdV
JvdV

Reputation: 75960

Assuming at least one occurence of the semi-colon is present, maybe chuck both options in their own group:

(?:\(([^;]+)|;\s*([^;)]+)\))

See an online demo

  • (?: - Open non-capture group;
    • \(([^;]+) - Match a literal open-paranthesis followed by a 1st capture group to match 1+ non-semicolon characters;
    • | - Or;
    • ;\s*([^;)]+)\) - Match a semicolon and 0+ whitespace characters before a 2nd capture group to match 1+ characters other than semicolon or closing paranthesis.

Another option is to match just these parts:

(?:\(|;.*;\s*|\G(?!^))\K[^;)]+

See an online demo

  • (?: - Open non-capture group;
    • \( - Match an open paranthesis;
    • | - Or;
    • ;.*;\s* - Match from 1st semicolon to last semicolon with possible 0+ whitespace chars;
    • | - Or;
    • \G(?!^) - Assert position at end of previous match but exclude start-line with negative lookahead;
  • \K - Reset starting point of reported match;
  • [^;)]+ - Match 1+ characters other than semicolon or closing paranthesis.

Upvotes: 2

Related Questions