开发者

Stripping out angle brackets with a regular expression

Having the following string:

<str1> <str2> <str3>

I am trying to do the regex such that I get the following 3 strings in C:

str1
str2
str3

I am trying to use the following regex but it doesn't seem to be yielding what I am aiming for:

<[a-zA-Z0-9]*.>

According to http://www.myregextester.com/index.php, that regex is going to yield

<str1>
<str2>
<str3>

How can I take out the <开发者_C百科;>'s?

Also, I'd also like to ONLY match strings with format, i.e., with 3 <>'s, no more, no less. How to approach that?


This can be easily done with a perl-compatible regular expression like this:

<([^>]+)>

You just have to make sure to tell your library to search for all matches, instead of trying to match the regular expression against the whole string. You will end up with str1, str2 and str3 as the first group match then.


What if you change it for <([a-zA-Z0-9]*.)>


<([a-zA-Z0-9]*?)> - Then you access the second match group of each match. (There is a PHP example on how to access the match group on http://www.myregextester.com/index.php

You can do this with positive lookaround ( http://www.regular-expressions.info/lookaround.html ) like this (?<=<)[a-zA-Z0-9]*(?=>) but not all flavours support it ( http://www.regular-expressions.info/refflavors.html )

Disclaimer: Don't copy Regex from the web if you do not understand how and why it works. This includes answers on Stack Overflow!


This regex would do the job:

/^<([a-zA-Z0-9]*?)>\s<([a-zA-Z0-9]*?)>\s<([a-zA-Z0-9]*?)>$/

example in Perl:

#!/usr/bin/perl
use 5.10.1;
use strict;
use warnings;

my $re = qr/^<([a-zA-Z0-9]*?)>\s<([a-zA-Z0-9]*?)>\s<([a-zA-Z0-9]*?)>$/;
my $str = q!<str1> <str2> <str3>!;
$str =~ s/$re/$1\n$2\n$3/;
say $str;

Output:

str1
str2
str3


You can simple use regex like given below to apply a check on angular brackets.

var text= "<span></span>";
var check = new RegExp(/[^>]\d+[a-z]*[^<])/ );
var valid = check text= 
if(!valid) {
return false;
} 
else
{
return true;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜