简体   繁体   中英

Javascript RegExp - it include space and brackets around

Bit of a noob to regexp

Please check out my attempt .

I want to isolate numbers that do not have hyphen or other characters around them apart from brackets - and then place quotes around these digits

so far I have - [^az-0-9](\\d+)[^0-9-az]

match group of digits - that does not start or end with numbers or charachters

It is currently matching (1, 2) instead of say 1 and 2

Test

(0-hyphen-number) OR
(123 no hyphen) OR
(no hyphen 2) OR
(no 3 hyphen) OR
(no -4- hyphen) OR
(no -5 hyphen) OR
(no 6- hyphen) OR
(blah 0987 hyp1hen) OR
(blah -4321 hyp-2hen) OR
(blah -1234- hyp3-hen)

Expected ouput :)

(0-hyphen-number) OR
("123" no hyphen) OR
(no hyphen "2") OR
(no "3" hyphen) OR
(no -4- hycphen) OR
(no -5 hyphden) OR
(no 6- hyphen) OR
(blah "0987" hyp1hen) OR
(blah -4321 hyp-2hen) OR
(blah -1234- hyp3-hen)

Your regex is close enough. You should however put - either at end or at beginning or character class.

You should capture all groups and replace them as follows.

Regex: ([^a-z0-9-])(\\d+)([^0-9a-z-])

Replacement to do: Replace with $1"$2"$3

Regex101 Demo

do not have hyphen or other characters around them apart from brackets

You should take note that your original regex [^az-0-9](\\d+)[^0-9-az]
matches any punctuation around the digits.

So, ,888+ and ,888] or *888} will match.

But what you're probably looking for is something like this

(?:^|[\\s()])(\\d+)(?:[\\s()]|$)

which only allows whitespace boundary or parenth's boundary.

Change [\\s()] to [\\s(] or [\\s}] to suite your needs.


Modification: To get possibly whitespace separated numbers as well.
https://regex101.com/r/pO4mO1/3

(?:^|[\\s()])(\\d+(?:\\s*\\d)*)(?:[\\s()]|$)

Expanded

 (?:
      ^ 
   |  [\s()] 
 )
 (                             # (1 start)
      \d+ 
      (?: \s* \d )*
 )                             # (1 end)
 (?:
      [\s()] 
   |  $ 
 )

By the time I loaded Regex101, it already had this working regex: [^az-0-9](\\d+)[^0-9-az]

FYI (for everyone confused), in earlier revisions of the post, the regex was ^az-0-9[^0-9-az] . Another user edited the post to reflect what they saw in the demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM