[英]Match text surrounded by underscore
我需要一个正则表达式来匹配:
_示例_Sample welcome text_
或Sample _welcome_ _text_
_欢迎_ _文本_
但不是Sample_welcome_text
即在开始下划线之前可以有(空格或没有)和结束下划线之后有(空格或没有)。
我试过使用这个:
/_(?:(?. ))(?*?)[^ ]_/gmi
虽然它有效但不幸的是它匹配Sample_welcome_text
您可以使用交替来以可选的空白字符后跟下划线开头,或者反过来。
请注意, \s
也可以匹配换行符。 如果需要,您可以只匹配空格,或者[^\S\n]*
排除换行符。
^\s*_.*|.*_\s*$
const regex = /^\s*_.*|.*_\s*$/; [ "Sample welcome text_", "Sample _welcome_ _text_", "Sample_welcome_text" ].forEach(s => console.log(`${s} --> ${regex.test(s)}`) )
您可以使用 lookbehind 和 lookahead assertion 来搜索被下划线包围的文本,并且在开始下划线之前可以有(空格或没有/字符串开头),在结束下划线之后可以有(空格或没有/字符串结尾)。
/(?<=[ ]+|^)_(.*?)_(?=[ ]+|$)/gmi
您可以对空格或字符串的开头/结尾使用正向后视和前视,并引用捕获组 1 中的单词: (.*?)
const regex = /(?<=\s|^)_(.*?)_(?=\s|$)/gs; [ "Sample welcome text_", "Sample _welcome_ _text_", "Sample_welcome_text" ].forEach(str => { let matches = [...str.matchAll(regex)].map(m => m[1]); console.log(str, '=>', matches); });
如果担心Safari不支持lookbehind,可以把lookbehind变成capture group,转而引用capture group 2:
const regex = /(\s|^)_(.*?)_(?=\s|$)/gs; [ "Sample welcome text_", "Sample _welcome_ _text_", "Sample_welcome_text" ].forEach(str => { let matches = [...str.matchAll(regex)].map(m => m[2]); console.log(str, '=>', matches); });
了解有关正则表达式的更多信息: https://twiki.org/cgi-bin/view/Codev/TWikiPresentation2018x10x14Regex
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.