user989818
user989818

Reputation:

regex match text in between

I get strings like:

"some text here /word/ asdhd"
"some other likehere/word1/hahas"
"some other likehere/dhsad huasdhuas huadssad/h ah as/"

What I need is to get the string between the two slashes, 'word', 'word1', 'dhsad huasdhuas huadssad' and 'h ah as'.

What is a regex for that?

Upvotes: 2

Views: 2501

Answers (4)

FailedDev
FailedDev

Reputation: 26930

Edit in case you have more than one of those words and want to iterate through them. *Edit again since question was changed.*

var myregexp = /\/(.+?)(?=\/)/g;
var match = myregexp.exec(subject);
while (match != null) {

        // matched text: match[1]

    match = myregexp.exec(subject);
}

Explanation :

    // \/(.+?)(?=\/)
// 
// Match the character “/” literally «\/»
// Match the regular expression below and capture its match into backreference number 1 «(.+?)»
//    Match any single character that is not a line break character «.+?»
//       Between one and unlimited times, as few times as possible, expanding as needed (lazy) «+?»
// Assert that the regex below can be matched, starting at this position (positive lookahead) «(?=\/)»
//    Match the character “/” literally «\/»

Upvotes: 5

Alex Turpin
Alex Turpin

Reputation: 47776

"some text here /word/ asdhd".match(/\/(.+)\//)

If you want to match more than one occurence in the same string, you need to use exec. See @FailedDev's answer.

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78520

var string = "some other likehere/dhsad huasdhuas huadssad/h ah as/";
var matches = string.match(/[/](.*)[/]/)[1];

That should do it.

EDIT revised to match new criteria.

Upvotes: 1

Drew Chapin
Drew Chapin

Reputation: 7989

\/[a-zA-Z0-9]+\/

\/ matches slashes
[a-zA-Z0-9] matches any letters uppercase or lower, and any numbers
+ means one or more

Upvotes: 0

Related Questions