我需要一个正则表达式来从字符串中获取数据,直到逗号。但是,我需要确保如果字符串没有逗号,我仍然会抓取整个字符串。
示例:我需要下面字符串中的大写字母 “这是第一部分,这是第二部分” “这是唯一的一部分”
答案 0 :(得分:1)
我们$&
的完全匹配(通常为/^[^,]*/
)或使用/^([^,]*)/
答案 1 :(得分:0)
答案 2 :(得分:0)
尝试
^(.*?)(?=,|$)
^ asserts position at start of a line
.*? matches any character (except for line terminators)
*? Quantifier — Matches between zero and unlimited times, as few
times as possible, expanding as needed (lazy)
Positive Lookahead (?=,|$)
Assert that the Regex below matches
1st Alternative ,
, matches the character , literally (case sensitive)
2nd Alternative $
$ asserts position at the end of a line
如果仅需要匹配(无捕获),请删除.*?
周围的括号,即^.*?(?=,|$)
。