How to extract information via regular expression?

Asked

Viewed 314 times

0

I have the following string:

adapter-UDP02_sistem10_a.log

How to extract the stretch UDP02 via regular expression? The logic being: capture everything after the - (hyphen) and before the first _ (underline)

  • If you follow this pattern where the hyphen - comes before the underline _, this regex can be used: [^-_]+?(?=_), in which only the first full match can be captured. But in cases like: error_adapter-UDP02_system10_a.log would not work. So I believe that Valdeir’s response to the use of the groups is the most appropriate.

1 answer

3


Utilize -(.*?)_.

- Starts the selection of the hyphen

(.*?)_ Here is the sign of ? will limit until the first occurrence of _

Demonstration
Demo with PHP
Demonstration with Java

Demo with Javascript

const regex = new RegExp("-(.*?)_");
const value = "adapter-UDP02_sistem10_a.log";

let result = value.match(regex);

console.log( result[1] );

  • In the online regex it is returning 2 groups (full Match and Group 1), it is possible to return only the value UDP02

  • Just capture the group. '-'. Ex: https://ideone.com/woq6p2 or https://ideone.com/8PDy2K .

  • @Fábiojânio The answer is this. You won’t be able to catch it without a group. JS only accepts lookbehind in Chrome (as far as I know). I think with lookbehind I could catch without group.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.