简体   繁体   English

使用正则表达式从复杂的字符串中获取项目

[英]Getting item from complex string using Regex

I'm new to regex and I am trying to get the string tumblr_nk8j5bEGc01u59obp (dynamic, not static) from below. 我是regex的新手,我正尝试从下面获取字符串tumblr_nk8j5bEGc01u59obp (动态,而非静态)。 I don't really know where to begin, could somebody please help me? 我真的不知道从哪里开始,有人可以帮我吗? (Java) (JAVA)

<embed type="application/x-shockwave-flash" src="https://secure.assets.tumblr.com/swf/audio_player.swf?audio_file=https%3A%2F%2Fwww.tumblr.com%2Faudio_file%2F80stmntsoundthingies%2F111871866039%2Ftumblr_nk8j5bEGc01u59obp&color=FFFFFF" height="27" width="207" quality="best" wmode="opaque"></embed>

I agree with Mathemats that I wouldn't use regex for this particular purpose. 我同意Mathemats的观点,我不会将regex用于此特定目的。

I'd do something like the following: 我会做如下的事情:

public static String isolateTumblrCodeFromURL(String url) {
    int start = url.indexOf("tumblr_");
    if (start == -1) return null;
    int end = url.indexOf('&', start);
    if (end == -1) return null;
    return url.substring(start, end);
}

Of course, you could use regex too, but this seems simpler and faster. 当然,您也可以使用regex,但这似乎更简单,更快捷。

In addition, this only works if there is only a single instance of the "tumblr_" String that you're looking for. 另外,这仅在要查找的"tumblr_"字符串的单个实例中有效。 If you need multiple, just wrap that logic in a loop controlled by int start = url.indexOf("tumblr_"); start>=0; start = url.indexOf("tumblr_", start) 如果需要多个,只需将该逻辑包装在一个由int start = url.indexOf("tumblr_"); start>=0; start = url.indexOf("tumblr_", start)控制的循环中int start = url.indexOf("tumblr_"); start>=0; start = url.indexOf("tumblr_", start) int start = url.indexOf("tumblr_"); start>=0; start = url.indexOf("tumblr_", start) int start = url.indexOf("tumblr_"); start>=0; start = url.indexOf("tumblr_", start) , and replace the return s with add s to your datastructure of choice. int start = url.indexOf("tumblr_"); start>=0; start = url.indexOf("tumblr_", start) ,并将return s替换为您选择的数据结构中的add

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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