簡體   English   中英

無法弄清楚需求的正則表達式模式(javascript拆分模式)

[英]Cannot figure out regex pattern for requirements (javascript split pattern)

我一直試圖找出以下字符串和要求的正則表達式模式。

this. i s.a.string .but. so is . this

預期結果:

1 - "this. i s"
2 - "a"
3 - "string .but. so is . this"

必須完成分離. 但是,如果它之前或之后有空格,那么它應該是前面結果的一部分。

我一直在嘗試以下變化(結果)

/[(^?=\.]+|[^?<=\.]+/g
1 - "this"
2 - "."
3 - " i s"
4 - "."
5 - "a"
6 - "."
7 - "string"

/[^?<=\.]+/g OR /[^\.]+/g
1 - "this"
2 - " i s"
3 - "a"
4 - "string"

編輯:更新字符串和預期結果。 基於我在評論/答案中看到的不確定性已被刪除。

你可以嘗試這樣的事情:

邏輯:

  • 尋找模式not space . 其次是not space ,並取代第一not spacenot space|
  • 現在拆分使用|. 獲取您的組列表

 function getGroups(str){ var replaceRegex = /(\\S)(?=\\.\\S)/g; var g = str.replace(replaceRegex, "$1|").split("|."); console.log(g) return g; } getGroups("this. i sastring"); getGroups("this . i sastring"); getGroups("this . i 1.a.string"); getGroups("127.0.0.1"); 

試試這個正則表達式:

[^. ]+(( \.|\. | )[^. ]*)*

這里它是如何工作的。

有了lookahead和后lookbehind ,分裂正則表達式將是:

(?<! )\.(?! )

但JavaScript不支持后面的觀點,其中一個技巧是:

var s = "this. i s.a.string .but. so is . this";
s.replace(/([^ ])\.(?! )/g, "$1__special__").split("__special__")
  1. 將帶lookahead和后面組捕獲的分隔符替換為特殊分隔符
  2. 由新的特殊分隔符拆分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM