-3

I would like to keep 456 with a regex from the following string:

jo​hn​#456 18 mai 2017 11:01

I tested with

#(.*) 

But I keep 456 18 mai 2017.

Mistalis
  • 17,793
  • 13
  • 73
  • 97
Stéphane GRILLON
  • 11,140
  • 10
  • 85
  • 154

2 Answers2

1

You can use the following regex, that will extract the number after your #:

.+#(\d+ )

Tested on the following data:

 jo​hn​#456 18 mai 2017 11:01
test123#123 18 mai 2017 11:01
michael#4561218 mai 2017 11:01
'(çà'_(fdlfsnd#456 18 mai 2017 11:01
lrjdlfddfdf#456 18 mai 2017 11:01

The regex extracts:

456
123
4561218
465
465

Here is a demo on Regex101

Javascript solution:

const regex4id = /.+#(\d+)/g;
var text = "jo​hn​#456 18 mai 2017 11:01"
var id =  text.match(regex4id);
if(id != null) {
    p = regex4id.exec(text);
    console.log("p: " + p[1]);
}
Mistalis
  • 17,793
  • 13
  • 73
  • 97
0

Using Lookahead and Lookbehind:

To get left of # and before the next space, you could also use a positive lookbehind and lookahead if you wanted it as a full match without using capturing groups:

(?<=#)\w+(?=\s)
  • (?<=#) is a positive lookbehind which ensures that # preceeds the match
  • \w+ matches one or more characters (includes alphabets, numbers and underscore)
  • (?=\s) is a positive lookahead which ensures that a space \s follows the match

Regex101 Demo

Learn more about lookaheads and lookbehinds here.

Using a capturing group:

You can also do it faster using a capturing group instead of lookaheads and lookbehinds. (Though the difference is negligible when only performing it for one match)

#(\w+)\s

Here, you can extract it by referring to group 1 based on your language $1 or group[1]

  • # represents literal #
  • (\w+) represents one or more characters in a capturing group (which is the 1st capturing group
  • \s represents a single space

Regex101 Demo

Hope this helps!

Community
  • 1
  • 1
degant
  • 4,861
  • 1
  • 17
  • 29