abiieez
abiieez

Reputation: 3189

Regex to extract a string

I have a string as

Celcom10 | 105ABCD | Celcom

This is my regex (\s\w+) however this also capture the white space.

How do I write a regex to obtain the middle values 105ABCD excluding the pipe and whitespace ?

I only need a regex pattern since this will be inserted within a diagram which will be executed in an automated test.

Upvotes: 0

Views: 78

Answers (3)

Braj
Braj

Reputation: 46841

I need a regex (or maybe 3) to extract all the three words / number (excluding the whitespace and pipe)

Get the matched group from index 1. Here parenthesis (...) is used to capture the groups.

(\w+)

Live Demo

\w       match any word character [a-zA-Z0-9_]

Have a look at the sample code

Upvotes: 2

HamZa
HamZa

Reputation: 14921

This is pretty easy and straightforward if you split the string by: \s*[|]\s*

Explanation:

  1. \s* match optional whitespaces
  2. [|] match a literal pipe, | means or in regex but if you put it in a character class [] it loses it's meaning
  3. \s* match optional whitespaces

Sample code:

input = 'somenickname | 1231231 | brand';
output = input.split(/\s*[|]\s*/);

// Printing
for(i = 0, l = output.length;i < l;i++){
    document.write('index: ' + i + ' & value: ' + output[i] + '<br>');
}

Output:

index: 0 & value: somenickname
index: 1 & value: 1231231
index: 2 & value: brand

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174696

You could try this also

[^ |]+

Upvotes: 3

Related Questions