How to construct this regular expression?

Asked

Viewed 226 times

1

I’m trying to build a regular expression and it’s a little difficult.

I would like you to help me, and if possible explain how the computer works in relation to this expression that I am asking for.

I need to take everything at the beginning of a string, until a string group is found, for example:

I want to pick from the beginning of the string until it is found "2.8" or "6v" or "2p".

Thank you.

  • http://www.regexpal.com/ this tool helps too much in the construction of regular expressions.

  • Are those "2.8" or "6v" or "2p" strings dynamic right? are they in an array? or will you have to type by hand?

  • No! I’m going to set something around 3 or 4 groups of Strings that will always be these

2 answers

5


/^(.)+(?=([\d+]\.?[\d+]|\d\w))/g

^(.)+
(?=
    (
        [\d+]\.?[\d+]
        |
        \d\w
    )
)

This expression will get any text that comes before "0.0" or "0x".

Explanation of the expression:

  • ^(.)+ any text from the beginning of the string
  • (?=) the text shall be followed by the following expression:
  • [\d+]\.?[\d+] digit digit digit digit, or...
  • \d\w digit and a letter
  • Your solution was the one that worked the way I wanted, thank you!

0

/((^[\s\S]+)2\.8)|((^[\s\S]+)6v)|((^[\s\S]+)2p)/g

Explaining:

[\s\S] picks up everything.

+ takes all characters that meet the above condition, so "all of everything".

^ indicates the beginning of String, so I put before searching for "all".

After that, just put where you want the search to stop. The parentheses are for organizing purposes, to leave everything separated.

| is an "or" operator. I just put the same code 3 times, changing only the stop condition.

\. is to search by the point. I had forgotten to add but edited.

Here’s an example: http://regexr.com/3evn9

Browser other questions tagged

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