| View previous topic :: View next topic |
| Author |
Message |
caesar Mint Rubber

Joined: 14 Oct 2001 Posts: 3741 Location: Mint Factory
|
Posted: Mon Mar 09, 2020 9:44 am Post subject: Regexp match |
|
|
Hi,
would appreciate if someone with far better knowledge of regexp could help me out turning this regexp from PHP into TCL:
| Code: |
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
| Thanks.
PS: Taken from here cos it matches multiple patterns. _________________ Once the game is over, the king and the pawn go back in the same box. |
|
| Back to top |
|
 |
AlbozZz Voice
Joined: 26 Jan 2020 Posts: 3
|
Posted: Tue Mar 10, 2020 8:46 am Post subject: Hi |
|
|
The Tcl and PHP RE languages are quite similar in this area (there are areas where they diverge, but this RE doesn't use them). The behaviour of using a match array in PHP is much like using the -inline option to regexp and saving the result (a list) in a variable that can then be indexed into (e.g., with lindex). The wrapping %…%i part of the PHP code becomes the -nocase option. Finally, you'll want to put REs in Tcl in {braces}.
| Code: |
set match [regexp -inline -nocase {(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})} $url]
set youtube_id [lindex $match 1]
|
We can split that into more lines for readability.
| Code: |
set RE {(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})}
set match [regexp -inline -nocase $RE $url]
set youtube_id [lindex $match 1]
|
The first line here is storing the regular expression in a variable, and the second line applies the RE to whatever is in the url variable, storing the resulting list in the match variable for later examination. Which is a good match for what preg_match was doing over in PHP.
Since you only actually want the ID, that's easy too:
| Code: |
set RE {(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})}
regexp -nocase $RE $url --> youtube_id
|
If desired, you can embed the caselessness inside the RE, similar to the PHP case, by prepending
| Code: |
(?i): set RE {(?i)(?:youtube ...)}
|
|
|
| Back to top |
|
 |
caesar Mint Rubber

Joined: 14 Oct 2001 Posts: 3741 Location: Mint Factory
|
Posted: Tue Mar 10, 2020 12:11 pm Post subject: |
|
|
Great. Thanks! _________________ Once the game is over, the king and the pawn go back in the same box. |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|