문자열 내에서 URL을 찾기위한 정규식
문자열 내에서 URL을 찾는 데 사용할 수있는 정규식을 아는 사람이 있습니까? 전체 문자열이 URL인지 확인하기 위해 Google에서 많은 정규 표현식을 찾았지만 전체 문자열에서 URL을 검색 할 수 있어야합니다. 예를 들어, 내가 찾을 수 있도록하고 싶습니다 www.google.com및 http://yahoo.com다음 문자열 :
Hello www.google.com World http://yahoo.com
문자열에서 특정 URL을 찾고 있지 않습니다. 문자열의 모든 URL을 찾고 있으므로 정규식이 필요합니다.
이것은 내가 사용하는 것입니다
(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?
나를 위해 일하고 당신에게도 일해야합니다.
정규식이이 용도에 완벽하지 않다고 생각합니다. 여기 에서 꽤 단단한 것을 찾았 습니다
/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/igm
여기에 게시 된 다른 것들과 비교하여 몇 가지 차이점 / 장점 :
- 이메일 주소와 일치 하지 않습니다.
- localhost : 12345와 일치합니다.
moo.com없이http또는 같은 것을 감지하지 않습니다www
text = """The link of this question: https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string
Also there are some urls: www.google.com, facebook.com, http://test.com/method?param=wasd
The code below catches all urls in text and returns urls in list."""
urls = re.findall('(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+', text)
print(urls)
산출:
[
'https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string',
'www.google.com',
'facebook.com',
'http://test.com/method?param=wasd'
]
여기에 제공된 솔루션 중 어느 것도 내가 가진 문제 / 사용 사례를 해결하지 못했습니다.
내가 여기에 제공 한 것은 내가 지금까지 발견 / 만든 것 중 최고입니다. 처리하지 않는 새로운 엣지 케이스를 발견하면 업데이트하겠습니다.
\b
#Word cannot begin with special characters
(?<![@.,%&#-])
#Protocols are optional, but take them with us if they are present
(?<protocol>\w{2,10}:\/\/)?
#Domains have to be of a length of 1 chars or greater
((?:\w|\&\#\d{1,5};)[.-]?)+
#The domain ending has to be between 2 to 15 characters
(\.([a-z]{2,15})
#If no domain ending we want a port, only if a protocol is specified
|(?(protocol)(?:\:\d{1,6})|(?!)))
\b
#Word cannot end with @ (made to catch emails)
(?![@])
#We accept any number of slugs, given we have a char after the slash
(\/)?
#If we have endings like ?=fds include the ending
(?:([\w\d\?\-=#:%@&.;])+(?:\/(?:([\w\d\?\-=#:%@&;.])+))*)?
#The last char cannot be one of these symbols .,?!,- exclude these
(?<![.,?!-])
이 정규식 패턴이 원하는 것을 정확하게 처리한다고 생각합니다.
/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/
다음은 URL을 추출하는 스 니펫 예제입니다.
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string to filter goes here.";
// Check if there is a url in the text
preg_match_all($reg_exUrl, $text, $url,$matches);
var_dump($matches);
위의 모든 답변은 URL의 유니 코드 문자와 일치하지 않습니다. 예 : http://google.com?query=đức+filan+đã+search
솔루션의 경우 다음이 작동합니다.
(ftp:\/\/|www\.|https?:\/\/){1}[a-zA-Z0-9u00a1-\uffff0-]{2,}\.[a-zA-Z0-9u00a1-\uffff0-]{2,}(\S*)
URL 패턴이 있으면 문자열에서 검색 할 수 있습니다. 패턴 에 url 문자열의 시작과 끝이 표시 되지 ^않고 $표시 되는지 확인하십시오 . 따라서 P가 URL의 패턴이면 P와 일치하는 항목을 찾습니다.
링크 선택에 엄격해야하는 경우 다음을 수행합니다.
(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
자세한 내용은 다음을 참조하십시오.
URL 일치를위한 개선 된 자유롭고 정확한 정규식 패턴
짧고 간단합니다. 아직 자바 스크립트 코드에서 테스트하지 않았지만 작동 할 것 같습니다.
((http|ftp|https):\/\/)?(([\w.-]*)\.([\w]*))
너무 단순하지만 작동 방법은 다음과 같습니다.
[localhost|http|https|ftp|file]+://[\w\S(\.|:|/)]+
파이썬에서 테스트했고 문자열 구문 분석에 앞뒤에 공백이 있고 URL에 공백이없는 한 (이전에 본 적이없는) 괜찮을 것입니다.
그러나 사용하면 다음과 같은 이점이 있습니다.
- It recognises
file:andlocalhostas well as ip addresses - It will never match without them
- It does not mind unusual characters such as
#or-(see url of this post)
I found this which covers most sample links, including subdirectory parts.
Regex is:
(?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?
In case someone need regex with detecting Urls like these:
- https://www.youtube.com/watch?v=38XmKNcgjSU
- https://www.youtube.com/
- www.youtube.com
- youtube.com ...
I came up with this Regex:
((http(s)?://)?([\w-]+\.)+[\w-]+[.com]+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)
This is a slight improvement on/adjustment to (depending on what you need) Rajeev's answer:
([\w\-_]+(?:(?:\.|\s*\[dot\]\s*[A-Z\-_]+)+))([A-Z\-\.,@?^=%&:/~\+#]*[A-Z\-\@?^=%&/~\+#]){2,6}?
See here for an example of what it does and does not match.
I got rid of the check for "http" etc as I wanted to catch url's without this. I added slightly to the regex to catch some obfuscated urls (i.e. where user's use [dot] instead of a "."). Finally I replaced "\w" with "A-Z" to and "{2,3}" to reduce false positives like v2.0 and "moo.0dd".
Any improvements on this welcome.
I used this
^(https?:\\/\\/([a-zA-z0-9]+)(\\.[a-zA-z0-9]+)(\\.[a-zA-z0-9\\/\\=\\-\\_\\?]+)?)$
I used below regular expression to find url in a string:
/(http|https)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/
Using the regex provided by @JustinLevene did not have the proper escape sequences on the back-slashes. Updated to now be correct, and added in condition to match the FTP protocol as well: Will match to all urls with or without protocols, and with out without "www."
Code: ^((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?
Example: https://regex101.com/r/uQ9aL4/65
I use this Regex:
/((\w+:\/\/\S+)|(\w+[\.:]\w+\S+))[^\s,\.]/ig
: 그것은 같은 여러 URL에 대한 벌금을 작동 http://google.com , https://dev-site.io:8080/home?val=1&count=100 , 8080 / 경로 : www.regexr.com, 로컬 호스트. ..
두 점 또는 마침표 사이의 텍스트를 찾는 논리를 사용합니다.
아래 정규식은 파이썬에서 잘 작동합니다.
(?<=\.)[^}]*(?=\.)
텍스트의 URL 일치는 그렇게 복잡하지 않아야합니다.
(?:(?:(?:ftp|http)[s]*:\/\/|www\.)[^\.]+\.[^ \n]+)
https://regex101.com/r/wewpP1/2
이것은 가장 간단한 것입니다. 나를 위해 잘 작동합니다.
%(http|ftp|https|www)(://|\.)[A-Za-z0-9-_\.]*(\.)[a-z]*%
이것은 최고의 것입니다.
NSString *urlRegex="(http|ftp|https|www|gopher|telnet|file)(://|.)([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?";
참고 URL : https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string
'IT TIP' 카테고리의 다른 글
| 개조가 BEGIN_OBJECT로 예상되었지만 BEGIN_ARRAY였습니다. (0) | 2020.11.03 |
|---|---|
| 문자열에서 ASCII가 아닌 문자 제거 (0) | 2020.11.02 |
| gem install pg --with-pg-config 작동, 번들 실패 (0) | 2020.11.02 |
| 루비에서 악센트 부호가있는 라틴 문자를 어떻게 바꾸나요? (0) | 2020.11.02 |
| 문화에 관계없이 소수점 이하 자릿수 찾기 (0) | 2020.11.02 |
