Regex - Expression for catching limited fields

Asked

Viewed 83 times

2

I have the following string:

"Let's put some bits in your home"

Using regular expression, how could I get only the information from bits forward, getting:

bits in your home

That is, the other words are discarded.

Has anyone ever seen such a case?

2 answers

1

If you want to always pick up after the word 'bits', you can use this simple expression:

(bits[^\n]*)

It captures everything after (and including) the word 'bits' until it finds a line break.

See this example working

1


Much depends on the variations that the String input can have, and what characters you want to pick up.

The simplest case is:

(bits.*)

That catches bits + everything you have after.

Only that .* means "zero or more occurrences of any character".

If you don’t want some character types, or just want certain types (like letters, numbers or spaces), or any other rule, you can restrict more by using something like the one suggested by israel’s response.

For example:

(bits[a-zA-Z0-9 ]*)

[a-zA-Z0-9 ]* will take only letters, numbers or space (zero or more occurrences of any of these characters). Change the expression according to what you need.


By default, the . does not consider line breaks (\n and \r), although some languages/Apis allow you to configure this (example). I do not know if this applies to your case (since it has not been specified), but it is a point of attention.

Browser other questions tagged

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