Javascript regular expressions modifier U [duplicate]
Asked Answered
M

3

-2

I have a string

"{1} {2} {4} {abc} {abs}"

and the regular expression

/\{(.+)\}/g

In PHP regular expressions i can use modifier "U" (U modifier: Ungreedy. The match becomes lazy by default). If i use /\{(.+)\}/gU my response looks like this:

Array (5) [ "1", "2", "4", "abc", "abs" ]

In javascript no modifier U. Without this modifier my response looks like this:

Array (1) [ "1 2 4 abc abs" ]

How i can do this?

Menderes answered 17/4, 2016 at 18:50 Comment(3)
.+?... There's no option to do it by default but you can always do it manually...Supervision
Is expected result Array (5) [ "1", "2", "4", "abc", "abs" ] ?Megaspore
@Megaspore Yes ....!Brittney
K
2

One way is to make the + ungreedy by adding the ? modifier:

"{1} {2} {4} {abc} {abs}".match(/\{(.+?)\}/g)

Another way would be to replace . with "anything except closing brace":

"{1} {2} {4} {abc} {abs}".match(/\{([^}]+)\}/g)
Kessinger answered 17/4, 2016 at 18:52 Comment(2)
Why did you escape { character in your pattern? I think that's useless. regex101.com/r/eW0dF3/1Brittney
@Shafizadeh: I copy/pasted from the question. Useless but also harmless.Kessinger
B
0

You can remove all {s and explode the string per }. Something like this:

var str = "{1} {2} {4} {abc} {abs}";
var result = str.replace(/{|}$/g,"").split(/} ?/);
document.write(result);
Brittney answered 17/4, 2016 at 19:0 Comment(0)
M
0

Try RegExp /([a-z]+|\d+)(?=\})/ig to match a-z case insensitive or digit characters followed by }

"{1} {2} {4} {abc} {abs}".match(/([a-z]+|\d+)(?=\})/ig)

console.log("{1} {2} {4} {abc} {abs}".match(/([a-z]+|\d+)(?=\})/ig))
Megaspore answered 17/4, 2016 at 19:0 Comment(1)
I think your pattern could be simply this /(\w+)(?=})/g. You don't need to escape { character, Also what OP mentioned in his question is just an example. I guess there maybe are some values like these: 1a, ba3.Brittney

© 2022 - 2024 — McMap. All rights reserved.