Home > Net >  Regex to match numbers, special chars, spaces and a specific whole word?
Regex to match numbers, special chars, spaces and a specific whole word?

Time:10-27

I'm trying to create a Regex to match numbers, special chars, spaces and a specific whole word ("ICT").

Example for the string:

[Columbia (ICT-59)]

Currently I've this Regex to match the numbers, special chars and spaces:

[\W\s\d]

And this one to for the word "ICT":

(ICT)

How can I match both of this in one Regular expression?

CodePudding user response:

use regex:

/(?<=\[)[a-zA-Z] \s\(ICT-\d \)(?=\])/g

or

/^\[[a-zA-Z] \s\(ICT-\d \)\]$/g

You can use \w at the position of [a-zA-Z], if you want to allow digits and special characters at the position of the Location.

demo:

https://regex101.com/r/ZS0jeO/1

https://regex101.com/r/hpQok3/1

CodePudding user response:

You could capture the part the you want in a capture group right after the opening [ and match the rest of the format.

\[([^()] ?)\s*\(ICT-\d \)]
  • \[ Match [
  • ([^()] ?) Capture group 1, match 1 chars other than ( or ), as few as possible
  • \s* Match optional whitespace chars
  • \(ICT-\d \) Match (ICT- 1 digits and )
  • ] Match literally

Regex demo

Or matching just a single word using \w

\[(\w )\s*\(ICT-\d \)]

Regex demo

  • Related